Script Valley
Node.js: The Complete Runtime
Express.js: Building REST APIsLesson 4.2

Express middleware: how it works and how to write your own

middleware signature, next(), error-handling middleware, application vs router middleware, morgan, cors, request timing middleware, middleware order

Middleware Is Just a Function

Every Express middleware is a function with the signature (req, res, next). Call next() to pass control to the next middleware; call next(err) to jump to the error handler; send a response to end the chain.

function requestTimer(req, res, next) {
  const start = Date.now();
  res.on('finish', () => {
    const ms = Date.now() - start;
    console.log(req.method + ' ' + req.path + ' โ€” ' + ms + 'ms');
  });
  next();
}

app.use(requestTimer);

Error-Handling Middleware

A four-argument function (err, req, res, next) is an error handler. Register it last:

app.use((err, req, res, next) => {
  console.error(err.stack);
  const status = err.status || 500;
  res.status(status).json({ error: err.message || 'Internal server error' });
});

Useful Third-Party Middleware

const morgan = require('morgan');
const cors = require('cors');

app.use(morgan('dev'));
app.use(cors({ origin: 'https://example.com' }));
app.use(express.json());
app.use(express.static('public'));

Up next

Input validation in Express APIs with Zod or Joi

Sign in to track progress

Express middleware: how it works and how to write your own โ€” Express.js: Building REST APIs โ€” Node.js: The Complete Runtime โ€” Script Valley โ€” Script Valley