Express middleware

Middleware is a function that have access to request object, response object and the next function in the application's request-response life cycle.

The next function is a function which can be called when the code in the middleware has completed.

When next function is called, it would move on to the next middleware if available or moves to the request api function.

Lets have a look into an example program for middleware.

const express = require("express");
const app = express();

// Logger middleware
const logger = (request, response, next) => {
  console.log(
    `URL - ${request.url};Method -  ${request.method};Time - ${new Date()}`
  );
  next();
};

// Error handling middleware
const errorHandler = (err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send("Unknown error has occurred.");
};

app.use(logger);

const port = 5000;

app.get("/ping", (request, response) => {
  response.send("Application running successfully.");
});

app.get("/error", (request, response) => {
  throw new Error("Something went wrong.");
});

app.use(errorHandler);

app.listen(port, () => {
  console.log(`Server running in port ${port}.`);
});

Output

Server running in port 5000.

URL - /pings;Method - GET;Time - Wed Nov 20 2019 21:16:33 GMT+0530 (India Standard Time)

In the above program, we use app.use to make logger() function and errorHandler() function to act as a middleware.

Whenever any request is received, then the request is passed to logger function before the api call handling.

The logger middleware function will log the url, method and time of request as shown in the output. Then next() function is called, which will pass the request to the appropriate api and the request is handled by the api.

The error handling middleware will have an additional error parameter which holds the error information. This middleware is called whenever an error is thrown. In the above program, if http://localhost:5000/error api is called, it will throw an error. The error will be caught by the errorHandler() middleware returns Unknown error has occurred. as response.



LATEST ARTICLES

Upload Files in NodeJS

EventEmitter in Nodejs

MongoDB Integration in Express Application

Structuring an Express Application in Nodejs

Sending email with Nodejs

Route module in nodejs

File System in NodeJs

Module in NodeJs

Using Express Middleware

How to start with Express framework in NodeJs

Back to articles