What Is Middleware?
Middleware functions have access to the request, response, and next function. They can execute code, modify req/res, end the request-response cycle, or call next().
Custom Middleware
// Logging middleware
function logger(req, res, next) {
console.log(`${req.method} ${req.url} - ${Date.now()}`);
next();
}
// Timing middleware
function timer(req, res, next) {
const start = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.url} took ${Date.now() - start}ms`);
});
next();
}
app.use(logger);
app.use(timer);
Route-Specific Middleware
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
// verify token...
next();
}
app.get('/api/profile', authMiddleware, (req, res) => {
res.json({ user: req.user });
});
Error-Handling Middleware
// Must have 4 parameters to be recognized as error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({
error: process.env.NODE_ENV === 'production' ? 'Server error' : err.message
});
});