Familiarize Yourself with Middleware Functions

Learn and implement the middleware functions in Express.js.

We'll cover the following

Before moving to implementation, we need to understand middleware functions. Our API rate-limiting function is actually going to be a middleware function that can be reused in any of the API routes, with a configurable window and the maximum number of API calls allowed per IP address in that window.

What are middleware functions?

In Express.js, middlewares are functions that have access to the request (req) and response (res) objects in the application's request-response cycle. They can perform various tasks, such as modifying request or response objects, executing code before or after the request is handled, or terminating the request-response cycle. Middleware can be used to:

  • Execute code before the request is processed by the route handlers.

  • Modify the request or response objects by adding or modifying properties.

  • Perform authentication and authorization checks.

  • Log requests and responses.

  • Handle errors and exceptions.

  • Implement additional functionality, such as compression, caching, or rate limiting.

A middleware function can be used by using the app.use() and app.get() methods (or other HTTP method functions like app.post(), app.put(), etc.) in Express.js. It takes three arguments: req, res, and next. The next argument is actually a function that passes the control to the next middleware in the chain or the route handler. We need to understand an important difference in using middleware with:

  • The app.use() method: The app.use() method is used to register a middleware function that is executed for every incoming request, regardless of the HTTP method (GET, POST, etc.) or the specific route being accessed. This means that the middleware is applied to all routes in our application. It's typically used for global middleware that needs to be executed for every request, such as logging, parsing request bodies, or setting up authentication.

  • The app.get() method or other HTTP method functions like app.post(), app.put(), etc.: These methods are used to define route-specific middleware. They specify that the middleware should only be executed for requests like GET, POST, PUT, etc., that match the specified route. This allows us to apply middleware functions selectively based on the route and HTTP method.

Let’s understand middleware functions better by taking an example. We’ll create global middleware using the app.use() method so that this middleware will be executed every time for all the APIs in our application. We’ll also implement a local middleware specific to a route that would only execute for a given API route. Finally, we’ll return some messages to know which middleware is called in our application.

Get hands-on with 1200+ tech skills courses.