Middleware (Express)

Middleware in Express is a function that runs during request handling, receiving (req, res, next). It can inspect or modify the request and response, end the response, or call next() to pass control to the next middleware.

Node.js

Middleware is Express's central concept. Each request flows through a stack of middleware functions in the order they were registered with app.use() or attached to a route. A middleware does its job — logging, parsing the body, checking auth — then calls next() to hand off to the following one, or sends a response to end the chain.

Common middleware includes express.json() (parses JSON request bodies into req.body), express.static() (serves static files), CORS handling, request logging (morgan), and custom auth checks that verify a token and either attach req.user or respond 401. Order matters: body parsers and auth must run before the routes that need them.

Error-handling middleware is special — it takes four arguments (err, req, res, next) — and Express routes errors to it when you call next(err) or throw in an async handler. Centralizing error responses there keeps individual routes clean.

Syntax

app.use((req, res, next) => { ...; next(); });

Examples

JavaScript

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

app.use(express.json());            // parse JSON bodies
app.use((req, res, next) => {        // simple logger
  console.log(req.method, req.url);
  next();
});

app.post("/echo", (req, res) => res.json(req.body));

Learn it in a lesson

See also

Back to the Dictionary