In Express.js, middleware refers to functions that are executed during the lifecycle of a request-response cycle. Middleware functions have access to the request (req
) and response (res
) objects, as well as the next function that allows you to pass control to the next middleware function in the stack.
Middleware can be used for various purposes such as:
-
Processing incoming requests (parsing body data, handling authentication)
-
Logging requests
-
Handling errors
-
Serving static files
-
Modifying request/response objects
How Middleware Works in Express
Express processes middleware in a stack, meaning that each middleware function is executed sequentially, one after the other, in the order they were defined. Each middleware function has three arguments:
-
req
: The request object, which contains the HTTP request data (headers, body, query parameters, etc.). -
res
: The response object, which allows you to send a response back to the client. -
next
: A function that, when called, passes control to the next middleware function. If not called, the request will hang.
Basic Syntax for Middleware in Express
Types of Middleware in Express
-
Application-Level Middleware
This type of middleware is bound to the Express app and can handle requests for all routes or specific routes.Specific Route Middleware:
Router-Level Middleware
This middleware is bound to a specific instance ofexpress.Router()
and only runs for routes handled by that router.Built-in Middleware
Express comes with some built-in middleware functions. For example:-
express.json()
: Parses incoming requests with JSON payloads. -
express.urlencoded()
: Parses incoming requests with URL-encoded data. -
express.static()
: Serves static files (images, CSS, JavaScript).
Example:
-
Error-Handling Middleware
This is a special type of middleware used to handle errors. It takes four arguments:err
,req
,res
, andnext
.Example:
This middleware is added after all other middleware functions and routes, and it's triggered if an error occurs anywhere during the request handling process.
Example of Using Middleware in an Express App
Here's a more complete example that uses multiple middleware functions:
When to Use Middleware
Middleware is useful in various scenarios, including but not limited to:
-
Request logging (e.g., logging each request for debugging or analytics)
-
Authentication and authorization (e.g., checking if a user is logged in or has permission)
-
Data parsing (e.g., parsing JSON or form data)
-
Static file serving (e.g., serving images, CSS, and JS files)
-
Error handling (e.g., catching and handling errors in your app)
Order of Middleware Execution
Middleware functions in Express are executed in the order they are defined, so the order in which you declare them matters. For example, if you declare an authentication middleware after a route handler, it will never be executed because the request is already responded to by the route.