Creating Custom Middleware
Middleware in Express is a function that sits between an incoming request and the final route handler. Custom middleware is middleware you write yourself to handle a concern shared by many routes, such as logging, checking a login token, timing requests or rejecting malformed input. Instead of copying the same lines into every handler, you write them once and plug them in where needed.
The shape of a middleware function
A middleware function receives three arguments: req, res and next. It can read or change the request and response objects. When it is done, it must either send a response or call next() to pass control to the next function in line. Express runs middleware in the exact order you register it.
const express = require('express');
const app = express();
// 1. Logs method, path and how long the request took
function requestTimer(req, res, next) {
const start = Date.now();
res.on('finish', () => {
const ms = Date.now() - start;
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} - ${ms}ms`);
});
next();
}
// 2. A middleware factory: returns middleware configured by its argument
function requireRole(role) {
return (req, res, next) => {
if (req.user?.role !== role) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
app.use(requestTimer); // every request
app.use(express.json());
app.delete('/api/users/:id', requireRole('admin'), (req, res) => {
res.status(204).end();
});
Where you can attach it
- Application level:
app.use(fn)runs for every request. Add a path, as inapp.use('/api', fn), to limit it to URLs beginning with that prefix. - Route level: pass one or more functions before the handler, as with
requireRole('admin')above. - Router level: call
router.use(fn)on anexpress.Router()so it applies only to that group of routes.
Order is not just a detail. A logger registered after the routes never sees requests the routes have already answered, and an authentication check placed after express.static() cannot protect the static files. Register general middleware, such as parsers and loggers, first, then authentication, then routes, and finally the error handler.
Sharing data with later handlers
Middleware often attaches information to req for code further down the chain. Authentication middleware might set req.user, and a request ID middleware might set req.id. For values meant only for rendering, res.locals is the conventional place.
Error-handling middleware
A middleware with four parameters, (err, req, res, next), is treated as an error handler. Express skips it during normal flow and jumps to it when any earlier function calls next(err) or throws synchronously. Register it last, after all routes.
In Express 4, an error thrown inside an async handler is not caught automatically. Wrap the body in try/catch and call next(err), or the request will hang and Node will report an unhandled rejection.
A minimal error handler logs the error and sends a generic message, for example res.status(err.status || 500).json({ error: 'Something went wrong' }). Avoid sending the raw error stack to clients in production, since it can reveal file paths and internal details.
The hanging request mistake
If middleware neither sends a response nor calls next(), the browser waits until it times out. This usually happens in an if branch that forgot one of them. The opposite mistake is calling next() after sending a response, which leads to the error "Cannot set headers after they are sent to the client". Using return res.status(...) when you reply early prevents both.
Takeaway
Every middleware ends by responding or calling next(). Order matters, factories let you configure middleware, and the four-argument version belongs at the end to catch errors.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.