DEV Community

Cover image for Express Middlewares
Shasheesh Purohit
Shasheesh Purohit

Posted on

11 5

Express Middlewares

Middlewares play a very important part in the request-response lifecycle. The middlewares are placed between the Server and the response.

The main role of middleware is to process the request in the middle before it is received by the Route Handler. The processing could be related to a variety of things such as :

  • Logging all requests coming to the server (Morgan is a very popular middleware used for this purpose)

  • To verify if the request has auth token or not (Passcode JS is a popular middleware for this purpose)

These are basically functions that can access request object, response object as well as the next middleware function in the application's request-response lifecycle (Next middleware function is commonly denoted by a variable named next).

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

Middlewares can be of various types, depending upon the different needs that are required by the programmer in the request.

Following are some of the types of Middlewares that are available based on your requirements:

  • Application Level Middleware
  • Router Level Middleware
  • Error Handling Middleware
  • Built-in Middleware
  • Third Party Middleware

Let us take an example of an application level middleware :

var express = require('express')
var app = express()

app.use(function (req, res, next){

 console.log('Time', Date.now())
 next()

})

Enter fullscreen mode Exit fullscreen mode

The above middleware is executed every time the app receives a request.

Mounting the middleare to a path:


app.use("/products/:id", function(req,res,next){
 console.log('Request Type: ', req.method)
 next()

})

Enter fullscreen mode Exit fullscreen mode

The above middleware is executed every time a request is received at the "products/:id" path.

Mounting to a path for a specific request:

app.get("/products/:id", function(req,res,next){
 res.send('product')
 next()

})

Enter fullscreen mode Exit fullscreen mode

The above middleware is executed every time we receive a GET request at the "products/:id" path.

Let us go in more depth about next() :

next() is used to propogate the request ahead. Calling next() is very important, if not called then it's basically a route handler and not a middleware.

One very important thing about middlewares is the order of the program or where the middleware has been used matters for the routes to effectively use it.

for eg:


app.use("/categories",categories)

app.use(middleware)

Enter fullscreen mode Exit fullscreen mode

Here the requests at "/categories" route will not be processed by the middleware hence for it to work properly we should define and use it at the top of all routes where we want the middleware to process the requests.

So we can say that middlewares provide a lot of help in implementing DRY and may be used at greater advantages to take some load off the server.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (3)

Collapse
 
steve_adolf_c8df300913217 profile image
STEVE ADOLF β€’ β€’ Edited

Nice post on middleware. I always put all my middlewares in middlewares folder. On of my favorate middleware(custom) is the middleware that i creates to add a user to the requests object.

/**
 * @param {Request} req
 * @param {Response} res
 */
const userIsAuthenticatedMiddleware = async (req, res, next) => {
  const token = req.headers["authorization"]?.split(" ")[1];
  if (!token) return res.status(401).json({ message: "Access denied" });

  try {
    jwt.verify(token, process.env.JWT_SECRET, (error, user) => {
      if (error) return res.status(401).json({ message: "Wrong token" });
      req.user = user;
      next();
    });
  } catch (error) {
    return res.status(500).json({ message: "Internal Server Error" });
  }
};

Enter fullscreen mode Exit fullscreen mode
Collapse
 
pankajpatel profile image
Pankaj Patel β€’

Great short post on middleware πŸš€

Collapse
 
shasheeshpurohit profile image
Shasheesh Purohit β€’

Thank you, appreciate the feedback πŸ™‚

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay