In Express.js, middleware is a function that sits between the client request and the server response.
It can inspect, modify, allow, or stop a request before it reaches the final route handler.
A middleware function can:
Read request data
Modify request or response objects
Execute code
End the request–response cycle
Pass control to the next middleware
Each middleware decides whether to:
Call next() → continue
Send a response → stop the chain
Applied to the entire app.
Applied to specific routes.
Provided by Express.
Installed using npm.
Examples:
morgan – logging
cors – enable CORS
helmet – security
Handles errors globally.
⚠ Must have four parameters.
Executed in the order they are defined
Order matters
Error middleware runs only on errors
Keep middleware small and focused
Always call next() when required
Place error middleware at the end
Avoid heavy logic in middleware
Reusable logic
Cleaner code
Better request control
Improved maintainability
Middleware processes requests before responses
Can modify, block, or pass requests
Express supports multiple middleware types
Execution order is critical
Take quizzes related to this topic and see where you stand!
Start Quiz Now