What Is Middleware?
Middleware is a function that runs between an incoming request and the outgoing response. It has access toreq, res, and next.
The Middleware Chain: next() Explained
1
Request arrives
Client sends HTTP request to the server.
2
First middleware runs
Express calls it with req, res, and next.
3
Call next() or end the response
If next() is called, execution moves to the next middleware. If res.send() is called, the cycle ends.
4
Route handler runs
Eventually a route matches and processes the request.
5
Response sent
The handler sends the response back to the client.
Built-in Middleware
express.json() must be registered BEFORE routes that read req.body. Without it, req.body is undefined.Third-Party Middleware
Install all three:Writing Custom Middleware
Request Logger
Request Timer
Authentication Check Middleware
Error-Handling Middleware
Error middleware is special: it has 4 parameters instead of 3. Express detects it by the 4-arg signature.Express Router
Useexpress.Router() to organize routes in separate files. This keeps app.js clean.
/api/v1/users.
Route Parameters vs Query Strings
Chaining Middleware on Routes
You can chain multiple middleware functions before the route handler:API Versioning
Prefix all routes with a version number from day one:Complete app.js Structure
Key Terms
Common Mistakes
Registering error handler before routes
Registering error handler before routes
Error-handling middleware placed before routes will never receive errors from those routes. Always put it last.
Confusing req.params and req.query
Confusing req.params and req.query
req.params.id is for URL path segments like :id. req.query.page is for query strings like ?page=2. They are not interchangeable.Not using express.json()
Not using express.json()
Without this middleware,
req.body is undefined. Every POST and PUT endpoint needs it.Forgetting to export the router
Forgetting to export the router
A router file that does not have
module.exports = router at the bottom will throw an error when imported in app.js.