Middleware
Introduction
Express middleware functions are in the middle of the client's request and the server's response. So they are executed in the middle of the request-response cycle. Middleware functions has access to the request and response objects. These functions are used to authentication, detect request headers, parsing request bodies, handling errors, etc...
Note
Middleware functions are executed in that order how they exists in the code.
In an Express each handler function is a middleware function - the signature of the handler function is identical to that of a middleware function. A middleware function might be something like a logging function, which logs the date and time of the request before passing it forward to the next middleware in the chain.
Logger example middleware
Below is a simple function that can be used as a middleware in Express. The next()
function is required for transferring the handling of the request to the next middleware or alternatively response can be sent to the client.
logger middleware | |
---|---|
1 2 3 4 5 6 7 8 9 |
|
Route level middleware
Created middleware function is assigned to a variable named logger
and can be used in application routes (route level).
index.js | |
---|---|
1 2 3 |
|
Application level middleware
Express application has use()
method which can be used to invoke middleware before wanted routes. This way middleware will be invoked before matched route.
index.js | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Above middleware should print following text to console with GET
request to /api/users
route. Notice how middleware function is called before the route function is called (prints route function
text to the console).
1 2 3 4 |
|
Usually middlewares are loaded before routes (not always, you need to know what you are doing and which order middlewares are needed to run). They send control to next middleware with next()
function.
A few middlewares
Here a a list of middlewares to check out:
- cors(), enable cors
- express.json(), change request JSON string to JSON object and put it to
request.body
- morgan, HTTP request logger middleware
Read more
Goals of this topic
Understand
- The concept of middleware in the context of Express.