Lesson 5 of 8Article16 min
Middleware, Validation, and Error Handling
Middleware runs in order and can inspect, transform, or reject requests. Good middleware design keeps auth, validation, and logging reusable across routes.
Middleware chain mental model
Middleware runs in order and can inspect, transform, or reject requests. Good middleware design keeps auth, validation, and logging reusable across routes.
Request logger and simple auth guard
function requestLogger(req, res, next) {
console.log(req.method, req.url);
next();
}
function authGuard(req, res, next) {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: "Unauthorized" });
}
next();
}
app.use(requestLogger);
app.get("/protected", authGuard, (req, res) => {
res.json({ secret: "Only for authenticated users" });
});Error middleware
- Call next(error) from route handlers.
- Do not leak stack traces in production responses.
- Normalize error shape for frontend consistency.
Centralized error handler
app.use((err, req, res, next) => {
console.error("Unexpected error:", err);
res.status(500).json({ error: "Internal server error" });
});