Creating your own Nodejs Middleware

Aditya Joshi
Aug 12, 2019 · 2 min read

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.

Aditya Joshi

Written by

I am a Blockchain Engineer, having a good experience in nodejs, Android, and latest technologies.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade