Using and understanding middleware

One of the most powerful features available with Express is the concept of middleware. The idea behind middleware is that it acts like a stack of filters that every request to your server passes through. Since every request passes through each filter, each filter can perform a specific task against the request before it passes through to the next filter. Typically, these filters are used for tasks such as cookie parsing, form field handling, session handling, authentication, and error handling and logging. The list goes on and on and you can use hundreds of third-party modules as well as simply write your own.

The order that the middleware is called in is very important. Again, using the concept of filters, as a request passes through each filter, you want to be sure that they are performing their responsibilities in the correct order. A great example of this is implementing a cookie parser before a session handler—since sessions typically rely on cookies to maintain state with a user between requests.

Another great example of how the order of middleware is important involves error handling. If any of your middleware encounters an error, they will simply pass that error along to the next middleware in the stack. If the last middleware, regardless of what it is, doesn't gracefully handle that error, it will basically show up in your application as a stack trace (and that's bad). Having an error handler configured as one of the last middleware is like saying if everything else fails, and at any point in the previous middleware a failure occurs, deal with it gracefully.

The various dependencies we have installed to use in this application are going to be integrated into our code as middlewares. We are going to carry out this task of integrating the various middlewares through the config module as it will help us to make our server.js file leaner to add more readability to the code base.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.56.28