Using middleware in Express
One of the greatest things about Express is that it is easily extended, which is achieved by using middleware. Every request makes its way through the middleware layer. In fact, our routes are just the final middleware function. We return a response, which means that at this point, the request is done and no more middleware functions are executed.
Creating our own middleware
To create our own middleware, all we have to do is create a function that accepts the parameters req
, res
, and next
. Inside of this function, we should have access to request and response, and the ability to tell Express to move on to the next piece of middleware.
To add a middleware layer to Express, we use app.use()
, which allows us to take a middleware ...
Get Building Scalable Apps with Redis and Node.js now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.