What is Middleware?

Middleware are functions that run during the request-response cycle, in order, before the final handler.

Syntax(req, res, next) => { /* ... */ next(); }

Middleware is the heart of Express. A middleware function receives req, res and next, and runs while a request is being processed. It can inspect or change the request, end the response early, or call next() to pass control along.

Every request flows through a chain of middleware and finally reaches a route handler that sends the response.

A request passes through a chain of middleware to a route, then a response is sentRequestloggernext()parse bodynext()route handlerResponse
Each middleware calls next() to hand the request to the next function in the chain.

Example

Example · javascript
const logger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // pass control to the next function
};

app.use(logger);

app.get('/', (req, res) => res.send('Home'));

When to use it

  • A developer adds a logging middleware that prints every incoming request method and URL before any route handler runs.
  • An authentication middleware checks for a valid JWT on every request to /api routes and rejects unauthorized callers.
  • A middleware function measures response time by recording a timestamp at the start and writing an X-Response-Time header at the end.

More examples

Minimal middleware example

Defines a middleware function that logs each request then calls next() to continue down the stack.

Example · js
function logger(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next(); // pass control to the next middleware
}

app.use(logger);
app.get('/', (req, res) => res.send('Hello'));

Middleware modifying req

Attaches a unique ID to req so every downstream handler and logger can correlate log entries.

Example · js
function addRequestId(req, res, next) {
  req.id = crypto.randomUUID();
  next();
}

app.use(addRequestId);

app.get('/trace', (req, res) => {
  res.json({ requestId: req.id });
});

Middleware that short-circuits

Returns a 401 immediately when the API key header is wrong, never calling next() and blocking the request.

Example · js
function requireApiKey(req, res, next) {
  const key = req.headers['x-api-key'];
  if (key !== process.env.API_KEY) {
    return res.status(401).json({ error: 'Invalid API key' });
  }
  next();
}

app.use('/api', requireApiKey);

Discussion

  • Be the first to comment on this lesson.