What is middleware?

Photo by Max Chen on Unsplash

What is middleware?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. These functions can be used to modify the request and response objects or to perform tasks such as authentication, logging, and error handling.

Middleware functions in Express.js are typically defined as follows:

function middleware(req, res, next) {
  // Perform some action
  // …
  next();
}

Middleware functions can be registered with an Express.js application using the app.use() method.

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

function logger(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next();
}

app.use(logger);

In this example, the logger middleware function will be called for every HTTP request made to the application. It logs the request method and URL to the console and then calls the next function to pass control to the next middleware function in the chain.

Middleware functions can perform the following tasks:

  • Execute any code.

  • Make changes to the request and the response objects.

  • End the request-response cycle.

  • Call the next middleware in the stack.

An Express application can use the following types of middleware:

  • Application-level middleware

  • Router-level middleware

  • Error-handling middleware

  • Built-in middleware

  • Third-party middleware