Middleware in Express.js
β± Estimated reading time: 2 min
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.
1. What Middleware Does
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
2. How Middleware Works (Flow)
Each middleware decides whether to:
-
Call
next()β continue -
Send a response β stop the chain
3. Types of Middleware in Express.js
3.1 Application-Level Middleware
Applied to the entire app.
3.2 Router-Level Middleware
Applied to specific routes.
3.3 Built-in Middleware
Provided by Express.
3.4 Third-Party Middleware
Installed using npm.
Examples:
-
morganβ logging -
corsβ enable CORS -
helmetβ security
3.5 Error-Handling Middleware
Handles errors globally.
β Must have four parameters.
4. Middleware Execution Order
-
Executed in the order they are defined
-
Order matters
-
Error middleware runs only on errors
5. Conditional Middleware
6. Custom Authentication Middleware (Example)
7. Best Practices
-
Keep middleware small and focused
-
Always call
next()when required -
Place error middleware at the end
-
Avoid heavy logic in middleware
8. Advantages of Middleware
-
Reusable logic
-
Cleaner code
-
Better request control
-
Improved maintainability
9. Summary
-
Middleware processes requests before responses
-
Can modify, block, or pass requests
-
Express supports multiple middleware types
-
Execution order is critical
Register Now
Share this Post
β Back to Tutorials