Chuck's Academy

Express JS

Advanced Middleware in Express

Middlewares are one of the most powerful and flexible components of Express. They allow us to intercept requests and responses throughout an application's lifecycle, giving us the ability to extend functionalities such as authentication, data validation, activity logging, and much more. In this chapter, we will delve into advanced middlewares and how to create custom middleware.

Types of Middleware in Express

There are different types of middleware in Express, each with a specific purpose within an application's flow. The most common are:

  • Application Middleware: Applied to the entire application and has access to every incoming request.
  • Route Middleware: Applied only to specific routes.
  • Error Middleware: Used to capture and handle errors.

Application Middleware

Application middlewares are applied to all routes of the application. They are ideal for global tasks such as request logging, session handling, or the use of CORS.

javascript
"This application middleware runs on every request that comes to the server. It logs the request time to the console using console dot log and then calls next to continue the flow."

Route Middleware

Route middlewares are applied only to a specific route. This allows adding additional functionalities to certain routes without affecting the rest of the application.

javascript
"This middleware called checkAdmin is applied only to the slash admin route. It checks if the request includes a query parameter admin with value true. If so, it allows the request to proceed; otherwise, it responds with a four hundred and three status code, Forbidden."

Error Middleware

Error middlewares are special because they are triggered when an error occurs in the application. They have four parameters: err, req, res, and next.

javascript
"This middleware captures any errors that occur in the application. It prints the error to the console with console dot error and then sends a response with a five hundred status code indicating something went wrong."

Creating Custom Middleware

In addition to using predefined or third-party middlewares, we can create our own custom middleware to add specific functionalities to our application.

Example of Custom Middleware for Data Validation

Next, we'll see how to create a custom middleware that validates the input data of a POST request.

javascript
"In this middleware called validateUserData, we verify that the POST request data includes a name and an email. If any of these fields are missing, we return a response with a four hundred status code. If the data is correct, we call next to let the request continue."

Third-Party Middleware

Besides creating custom middlewares, Express allows using third-party middlewares that add specific functionalities to the application. For example, body-parser is a middleware that allows us to process the request bodies, and cors is used to handle cross-origin security policies.

Installing and Using cors

bash
"We install the cors middleware using npm install cors to enable cross-origin security policies in our Express application."

Then, we configure it as global middleware:

javascript
"We use the cors middleware in our Express application by configuring it as global middleware so that all routes are protected against cross-origin issues."

Middleware for Improving Performance

Another advanced use of middlewares is to optimize an application's performance. We can, for example, implement middleware for HTTP response compression or to cache certain results.

Compression Middleware

The compression middleware allows compressing HTTP responses, which reduces the size of data sent to the client and improves loading times.

Installing compression

bash
"We install the compression middleware with npm install compression to reduce the size of HTTP responses and improve the application's performance."

Using compression

javascript
"We use the compression middleware in our application by configuring it as global middleware to automatically compress all HTTP responses."

Advanced Logging Middleware

In addition to improving performance, we can use middlewares to log detailed information about requests and responses, aiding in application monitoring. We've previously seen how to use Morgan for basic logging, but we can also create more personalized logging middlewares for specific needs.

Custom Middleware for Logging

Here’s an example of how to create a custom middleware that logs the time it takes to process each request:

javascript
"This middleware logs the time it takes to process each request. Initially, we log the time with Date dot now, and when the response finishes, we calculate the duration by subtracting the start time from the current time."

Best Practices with Middleware

  1. Order of Middlewares: The order in which the middlewares are defined is important, as they execute in the same order they were declared. Ensure the most general middlewares are at the beginning and the specific ones at the end.
  2. Reusing Middlewares: Take advantage of Express's modularity to reuse middlewares in different parts of the application or between projects.
  3. Avoid Long Processes in Middlewares: Middlewares should be efficient and not block the request lifecycle. If you need to perform heavy operations, consider making them asynchronous or using them in a separate layer.

Conclusion

In this chapter, we've explored the advanced concepts of middleware in Express, including creating custom middlewares, using third-party middlewares, and how to optimize application performance using middlewares. Proper use of middlewares can significantly improve the efficiency and security of an Express application.


Ask me anything