Creating your own Nodejs Middleware

Overview

Middleware functions are functions that have access to the request object (), the response object (), and the function in the application’s request-response cycle. The function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

If the current middleware function does not end the request-response cycle, it must call to pass control to the next middleware function. Otherwise, the request will be left hanging.

Example 1

This is a very basic example, which modifies the request object. It adds the current date and time to the request object, once the date and time are added to the request object, the request is forwarded to the next route.

To use the middleware in the application, app.use() function is used and the name of the middleware function is passed.

Example 2

In the above example we are setting up the middleware for only ‘/’ route, by passing the middleware function name. In this way we setup middleware according to the routes.

I am a Blockchain Engineer, having a good experience in nodejs, Android, and latest technologies. I am Certified Hyperledger Fabric Administrator (CHFA)

I am a Blockchain Engineer, having a good experience in nodejs, Android, and latest technologies. I am Certified Hyperledger Fabric Administrator (CHFA)