Table of contents
1.
Introduction
2.
What is Middleware?
3.
Middleware Chaining
4.
Implementing Middleware
5.
Advantages of Middleware
6.
Frequently Asked Question
7.
Key Takeaways
Last Updated: Mar 27, 2024

Middleware in Express

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Express is one of the most popular routing frameworks for node.js. No matter whether you are a MERN or MEAN stack developer the “E” remains constant which stands for Express.js. Express is a fast and minimalistic web framework for node.js

Middleware in express.js are the functions that are invoked by the routing layer of express.js before the final request handler. As it is pretty much clear by the name that middleware is a piece of code/function that appears between the two requests and responses. 

Middleware is very useful in the development of a website. In this article we will be discussing middleware in detail.

What is Middleware?

According to the express.js official documentation, middleware is defined as-

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.

As we discussed earlier, Middleware is the piece of code that sits between request and response. Middleware gets executed when the server receives a request and before the sending of a response. In fact, an express-based application is a series of middleware function calls.

Middleware in express.js 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.

 

The figure below shows the different elements involved in a middleware function in express.js


Now we are familiar with the basics of the middleware in express, let's discuss middleware chaining.

Middleware Chaining

Different middlewares in the express can be chained together, so whenever a request is sent to the server, it goes through a series of middleware, and the middleware are executed in the order in which they are chained. The last function sends the response back to the server.

To achieve the chaining in express next() function is used, which is responsible for calling the next middleware function.


In the above diagram, we can see that a request is being sent through different middleware and operations are being performed and the last middleware sends the response back to the server.

Now we know about middleware and middleware chaining, lets try to implement a simple middleware in the express.

Implementing Middleware


Before we start implementing middleware, make sure that you have Node.js installed on your PC. If you have Node.js installed, then create a new node project and install express as a dependency using the following command.

npm install express

Once the express is installed the create an app.js file in the directory. Now open the app.js file in any code editor of your choice and write down this code.

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

var myMiddleware = function (req, res, next) {
  console.log('Visited home page')
  next()
}

app.use(myMiddleware)

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000)



Output


Every time the app receives a request, “Visited home page “ is logged into the console.

Advantages of Middleware

Below are some of the advantages of using the middleware in express

  1. Middleware can be used to implement the login and authentication
  2. Middleware improves the client-side rendering.
  3. Middleware helps in optimization and better performance
  4. Middleware can be used for error handling.

Frequently Asked Question

  1. What is Middleware in Expree.js?
    Middleware functions 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 that, when invoked, executes the middleware succeeding the current middleware.
  2. What is middleware chaining?
    Different middlewares in the express can be chained together, so whenever a request is sent to the server it goes through a series of middleware and the middleware are executed in the order in which they are chained. The last function sends the response back to the server.

Key Takeaways

This article discussed middleware in js in detail, along with its syntax, use, and implementation. We also discussed the middleware chaining in detail.

You may check out Full Stack Web Development Course — Node.js + HTML/CSS/JS on Coding Ninjas

If you are preparing for the next interview, check out the blog's 15 Most Frequently Asked React JS Interview Questions and 10 Best ReactJS Interview Questions. And if you are a beginner, check out the Top 5 skills to learn before you start with ReactJs to know the prerequisites to learn React.

If you are preparing for your DSA interviews then, Coding Ninjas Studio is a one-stop destination. This platform will help you acquire effective coding techniques and give you an overview of student interview experience in various product-based companies.

Live masterclass