How Does NodeJS middleware work?

Friend’s here; we will try to understand how the Middleware works in the Nodejs. We will try to implement here own Middleware after that we will use Expressjs. Firstly we will try to understand what does Middleware means. After that, we will try to achieve our Middleware.

What is Middleware in the Nodejs?

Whenever we type any URL into our browser(client)
address bar. We are requesting information from the webserver where we want to do anything such as fetching any information. The server gets our request based on the requesting information. It interprets and prepares the response as per the request. It may have text, images any possible value.

When the webserver receives the request from the user in the form of data, the Nodejs gives you a request object. There will be the information on the browser, IP address, languages, and much more information in that object. Users can pass parameters also with that. After processing the request, NodeJs give back the response. These requests and responses are shortened to req and res.

Middleware functions are the best place to modify or update the req and res. For example, we are fetching the details of the user from the database. While fetching the data middleware will authenticate the user after authentication only webserver responds the exact data or the error that 401 (unauthorized access).
In a nutshell, we can say that. Middleware will give you access to the req and res. The next middleware function is a variable named next.

In short we can say that following for the Middleware:-

  1. As the names suggest, it comes in the middle of the request and response cycle.
  2. Middleware has access to re and res and req.
  3. Middleware has access to next for the request and response cycle.
Middleware in NodeJs

Middleware can do following tasks:

  1. Middleware execute the code
  2. Middleware make changes to request and response
  3. It can end the response cycle
  4. Middleware can execute the call that in the stack

These are the basic definitions of the Middleware in the NodejS. In the next section, we will learn what does next() do in the Middleware.

What is next() in the middleware?

Middleware is, in a nutshell, a function that will have access to the response cycle. In middleware, we can do many things, such as waiting for asynchronous databases or any network to proceed to the next step. We can take this example, and users are trying to edit the user information. In the middleware, we can check the authentication after properly authenticated we can check the authorization also. So in the middleware, we can do multiple things.

nodejs middleware next() example

In the above image, we can see the there we have taken an example in which we are updating the admin password. In that when the user will call the API to the web server, we will encrypt the data.
In the first phase, we will check that the login user is authenticated. If authentication fails, the web server will send a 401 error to the user.
After authentication, we will check the user is authorized to make the changes. If the user is authorized, the user will make changes, and the response cycle will complete. If the user is not authorized, the webserver will send a 401 error to the user.

Now we will see the types of middleware:

  1. Application-level middleware which generally uses app.use()
  2. Router level middleware which generally uses router.use()
  3. Built-in middleware like express
  4. The middleware which handled the error 
  5. There are some third ware middleware are there like cookieParser, bodyparser etc 

We will see examples for all the above middleware

  1. Application-level middleware

In the application level, we will take an example we have an eCommerce site there we have routes like:
checkOutProduct, getOrderDetails, isAdmin
Here all these API calls we do after the user is login into the system.
For that, we create a middleware in which before accessing the routes, it will check that the user is login or not.

const express = require('express');

// custom middleware create
const LoggerMiddleware = (req,res,next) =>{
    console.log(`Logged  ${req.url}  ${req.method} -- ${new Date()}`)
    // it will trigger next response if user is login it will return the data
    // otherwise return 401

const app = express()

// application level middleware

// get user orders route

//checkout product POST METHOD'/checkOutProduct',(req,res)=>{

// is admin'/isAdmin',(req,res)=>{

    console.log('server running on port 3002')

2. Router level middleware

In router level middleware, the same concept is there like application. In the application level, the middleware is at the application level in the route level middleware. It will protect a specific URL or route.
For example, there is one route in which the user wants to see all the transaction details.
But this is very confidential data, and only super admin has access to see the details. So there we need the router level. It will restrict unwanted access to the route.

const express = require('express');

const app = express();

const router = express.Router()

// route level middleware
router.use((req, res, next) => {

router.get("/user/paymentDetails/:userId", (req, res, next) => {
}, (req, res, next) => {
}, (req, res) => {
		status: true,

app.use('/', router)

app.listen(3000, (req, res) => {
	console.log('server running on 3000')

3. Third-party Middlewares

There are many third-party middlewares that we can install that module and use their functionality in our application. It will increase the speed of development. We can handle it at any level, like the application or the route level. For example bodyparser, cookieparser.

For installing the body parser run this command

 npm install body-parser
var express = require('express');
var  bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({extended:false})) // middleware 

var server = app.listen(3000, function() {
      console.log('Listenint Port : 3000 ');

4. Middleware which handled the error 

ExpressJS comes with default error handling params, which will act like middleware function in the same way as in application level and route level. For error handling, it comes with four parameters. For example

app.use(function (err, req, res, next) {
  res.status(500).send('Something Went wrong please check!')


I have tried my best to discuss and describe the middleware concept. In a nutshell, we can say that when the user requests anything on browser or API request is generated with the user input. When the call reaches the webserver, it evaluates it that it’s coming from the right sources or not before sending back the final response. It will do all the needful operation. The operation will take place; that part is middleware. After evaluating all the possibilities, it will acknowledge the proper response to the user. I hope you have all liked the Article. Please give your valuable comment.