What Middleware Is
Middleware is a function with access to the request, the response, and a next() function to pass control to the next middleware in the chain. Logging, authentication, parsing a request body, and error handling are all implemented as middleware in Express.
A Simple Logging Middleware
Console Output
Click “Run” to see the console output here.
Middleware Runs in Order
app.use() and route handlers form a chain, executed top to bottom in the order they are registered. Each middleware must call next() to continue to the next one — forgetting to call next() (or send a response) leaves the request hanging forever.
Middleware for a Specific Route Only
Console Output
Click “Run” to see the console output here.
Common Built-in and Third-Party Middleware
| Middleware | Purpose |
|---|---|
| express.json() | Parses a JSON request body |
| express.static(dir) | Serves static files from a folder |
| cors() | Handles Cross-Origin Resource Sharing headers |
| helmet() | Sets security-related HTTP headers |
| morgan() | HTTP request logging |
A Middleware That Never Calls next() Hangs the Request
If a middleware neither calls next() nor sends a response (res.send(), res.json(), res.end()), the request never completes — it just hangs until the client eventually times out.
Best Practice
Order matters — register broadly-applicable middleware (logging, CORS, body parsing) before your routes, and route-specific middleware (like auth checks) directly on the routes that need it.