Express.js
Beginner
1 min read
The Middleware Chain and next()
Example
const express = require('express');
const app = express();
app.use(express.json());
// Middleware 1 – rate limiter (simplified)
const hits = {};
function rateLimit(req, res, next) {
const ip = req.ip;
hits[ip] = (hits[ip] || 0) + 1;
if (hits[ip] > 100) {
return res.status(429).json({ error: 'Too Many Requests' });
}
next(); // pass to middleware 2
}
// Middleware 2 – auth check
function authenticate(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return next(new Error('No token provided')); // → error handler
req.userId = 'user-123'; // decoded from token in real code
next(); // pass to route handler
}
// Route with two middleware in sequence
app.get('/profile', rateLimit, authenticate, (req, res) => {
res.json({ userId: req.userId });
});
// Error-handling middleware (4 args, registered last)
app.use((err, req, res, next) => {
console.error(err.message);
res.status(err.status || 500).json({ error: err.message });
});
app.listen(3000);
Related Resources
Express.js Reference
Complete tag & property list
Express.js How-To Guides
Step-by-step practical guides
Express.js Exercises
Practice what you've learned
More in Express.js