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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.