agyanadda@gmail.com

Express.js Middleware

Express.js and Databases 1 min read Updated Dec 3, 2026 Topic 17 of 30

Middleware is a function that runs between the request arriving and the response being sent. It has access to req, res and next.

What middleware can do

  • Run code (logging, timing)
  • Change req or res (add req.user)
  • End the request (send a 401)
  • Call next() to pass control to the next middleware or route

If middleware neither responds nor calls next(), the request hangs.

Where to use it

  • For every request: app.use(logger)
  • For a path: app.use('/admin', requireAdmin)
  • For one route: app.get('/profile', requireLogin, handler)

Popular middleware packages

cors (allow other domains), helmet (security headers), morgan (request logs), express-rate-limit, cookie-parser, multer (uploads).

Error-handling middleware

Has four arguments (err, req, res, next) and goes after all routes. Call next(err) anywhere to jump to it. (Express 5 also passes errors from rejected async handlers to it automatically.)

Example

Example — Logger, auth check and error handler JavaScript
import express from 'express';
const app = express();

// 1. Runs for every request
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => console.log(`${req.method} ${req.url} ${res.statusCode} ${Date.now() - start}ms`));
  next();
});

// 2. Route-level middleware
function requireApiKey(req, res, next) {
  if (req.get('x-api-key') !== process.env.API_KEY) {
    return res.status(401).json({ error: 'Invalid API key' });
  }
  next();
}

app.get('/api/secret', requireApiKey, (req, res) => res.json({ data: 'top secret' }));

app.get('/boom', (req, res, next) => next(new Error('Something broke')));

// 3. Error handler: four arguments, defined last
app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.statusCode || 500).json({ error: 'Internal server error' });
});

app.listen(3000);

Every request is logged like "GET /api/secret 401 2ms". /api/secret needs the right x-api-key header. /boom is caught by the error handler, which returns a 500 JSON response.

Test Yourself With Exercises

Exercise 1 Multiple Choice

How many arguments does Express error-handling middleware take?

Exercise 2 True / False

Middleware that never calls next() or sends a response leaves the request hanging.

Exercise 3 Fill in the Blank

Pass control to the next middleware by calling ___()

Frequently Asked Questions

Body parsers, security (helmet, cors) and logging first, then authentication, then your routes, then the 404 handler, and the error handler at the very end.