Creating your own Nodejs Middleware

Overview

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next 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 next() 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)

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aditya Joshi

Aditya Joshi

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