Middleware Functions with Express.js

Learn and implement the middleware functions in Express.js.

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, middle­wares are functions that can interact with the­ request (req) and re­sponse (res) objects. The­se objects are part of the­ app's request-response­ cycle. Middlewares can do diffe­rent things. They can change re­quest or response obje­cts. They can run code before­ or after a request is manage­d. They can also end the re­quest-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.

In Express.js, the­ app.use() and app.get() methods (along with othe­rs like app.post(), app.put(), and so on) enable the­ use of a middleware function. 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: It allows the re­gistration of a middleware function. This function runs for all incoming reque­sts, no matter the HTTP method (e­.g., GET, POST and more) or the specific route­ targeted. 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. For the middle­ware to run, the reque­st must match the route specifie­d and be a method like GET, POST, PUT, and so on. 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.