Middleware in Nodejs with Example

Middleware in NodeJS with example

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")();
 
const 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 isUser = (req, res, next) => {
  ... // code to query the Database
  if(user){
    req.isUser = true;
    next();
  }
  else {
    res.status(403).send("user not found in IndGeek Database")
  }
}

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”.

// In the actual server the user Checking is done via the middleware
 
const app = require('express')();
const isUser = require('./middlewares/auth');
 
const getList = (req, res) => {
  if (req.isUser) {
    res.send('Found user in IndGeek Database');
  } else {
    res.status(403).send('Forbidden');
  }
}
 
const searchUser = (req, res) => {
   if(req.isUser) ...
}
 
app.get('/getdb', isUser, getList);
app.get('/api/search', isUser, searchUser);
 
app.listen(5000, ()=>{ console.log(`server started`) })

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

In other words, if the isUser function finds the user and calls the next() then it passes to the next function in the app.get('/getdb'). The isUser middleware modifies the object (req) before passing them to the next middleware function in the chain.

We can specify a middleware function with a path for which the function is to be called.

// app.use(path, middleware)
 
app.use(isUser);
 
app.get("/getdb", getList);
app.get("/api/search", searchUser);

The app.use(isUser) will enable the middleware function to load in each path request.

Advantages of middleware:

  • Middleware can be used to run authentication.
  • Can manipulate request objects before reaching the server
  • Clean code management
  • Improves client-side rendering performance
  • Middleware is used to set some specific HTTP headers.
  • Middleware helps with 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 (opens in a new tab). I hope this tutorial helped you sharpen the basics of middleware.

IndGeek provides solutions in the software field, and is a hub for ultimate Tech Knowledge.