Middleware in NodeJS with example

• Updated September 4, 2022

Middleware in NodeJS is one of the crucial concepts that shape the backend of a functional website.

nodejs middleware illustration

Express is a laboriously used package that comes in handy for serving files, routing, handling requests, and handling HTTP methods. Express helps in handling the different routing of the webpage and it works between the request and response cycle.

What is Middleware?

As the name already suggests, it is something that takes place in the middle. Think of this as an intermediary. They are middle functions and they get to decide if the next function is to be called or not.

Middleware functions have access to the request object, the response object, as well as the next function in the application’s request-response cycle.

const app = require('express')();

function getList(req, res){
  res.send("IndGeek DataBase")
}

app.get('/getdb', getList)

app.listen(5000, ()=>{ console.log(`server started`) })

This is a simple server with a single API route at /getdb

When any user lands on this route, the getList function is called with the request and response argument.

Also Read: How to send emails via Nodejs

As an example, in an application, if any user asks for a list of all existing data, they need to be checked as an existing user or not.

The code for the following would be:

const app = require('express')();

function isUser(req, res, next) {
  if(req.isUser){
    next()
  }
  else {
    res.status(403).send("cannot access IndGeek Database")
  }
}

function getList(req, res){
  res.send("IndGeek DataBase")
}

app.get('/getdb', isUser, getList)

app.listen(5000, ()=>{ console.log(`server started`) })

Middleware working

Here a middleware named isUser is created which receives the request, response, and next argument.

The middleware checks if the user exists, If it does, it calls next(), which means proceed to the next function that handles the API. If it doesn’t exist, it returns a forbidden status code, as well as a response, “cannot access IndGeek Database”.

while specifying get method isUser is called in a way that getList becomes the next function if isUser passes.

Advantages of middleware:

  • Middleware can be used to run authentication.
  • Can manipulate request objects before reaching the server
  • Optimization and better performance
  • Improves client-side rendering performance
  • Middleware is used to set some specific HTTP headers.
  • Middleware helps for Optimization and better performance.

Conclusion

Middleware in NodeJS is a crucial process to implement a lot of the above-discussed features and a major part of any full-fledged web application. It makes any Nodejs project cost-effective for the development and running of the application at scale.

If you’re looking to explore more into advanced middleware, you may check out the official express.js documentation here. I hope this tutorial helped you sharpen the basics of middleware.

Sharing Is Caring:
Soumya Mondal

An aspiring BTech Electronics and Communication student, obsessed with Coding, Gadgets, Blogging, & Digital Marketing.

Leave a Comment