Node.js Middleware Complete Guide
Ad
What is Middleware?
Middleware are functions that run between receiving a request and sending a response. Each has access to req, res, and next. They power logging, auth, parsing, and error handling in Express.
The Middleware Signature
function middleware(req, res, next) {
// do something
next(); // pass control to the next middleware
}
app.use(middleware);
Example: Request Logger
app.use((req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
next();
});
Example: Authentication Guard
function requireAuth(req, res, next) {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: "Unauthorized" });
req.user = verifyToken(token);
next();
}
app.get("/profile", requireAuth, (req, res) => {
res.json(req.user);
});
Built-in & Popular Middleware
| Middleware | Purpose |
|---|---|
| express.json() | Parse JSON bodies |
| cors | Enable cross-origin requests |
| helmet | Security headers |
| morgan | HTTP request logging |
Error-Handling Middleware (4 args)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: "Something broke" });
});
FAQs
Does middleware order matter?
Yes — middleware runs top to bottom. Put logging and body parsing early, error handlers last.
What if I forget next()?
The request hangs forever. Always call next() (or send a response). More in our Node.js guides.
