Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is ExpressJS?
3.
What is Middleware?
4.
Working On The Middleware Function
5.
Types of Middleware
5.1.
Application-level Middleware
5.2.
Router-level Middleware
5.3.
Error-handling Middleware
5.4.
Built-in Middleware
6.
Custom Middleware in ExpressJS
7.
Syntax 
8.
Parameters
8.1.
Request(req)
8.2.
Response(res)
8.3.
Next(next)
9.
Custom Middleware
9.1.
Code
9.1.1.
Output
9.2.
Explanation
10.
Advantages of Custom Middleware in ExpressJS
11.
Disadvantages of Custom Middleware in ExpressJS
12.
Frequently Asked Questions
12.1.
What is Middleware in ExpressJs?
12.2.
What is the purpose of custom middleware in ExpressJs?
12.3.
How to handle errors in custom middleware?
12.4.
Different types of Middleware?
12.5.
What will happen if we don't include the "next" command?
13.
Conclusion
Last Updated: Mar 27, 2024
Medium

Custom Middleware in ExpressJS

Author Vidhi Sareen
0 upvote

Introduction

Do you ever wonder how web applications handle complicated tasks like authentication, logging, error handling, or input validation? Behind the scene, a robust mechanism named Middleware is at work. Middleware bridges incoming requests and outgoing responses, allowing you to include custom functionalities in your ExpressJS application.

Custom Middleware in ExpressJS

This article will discuss Custom Middleware in ExpressJS and how it can construct your web applications more powerful and flexible.

What is ExpressJS?

ExpressJS is an open-source web application framework for Node.js that delivers developers with a minimalistic and relaxed approach to constructing applications. Designed and sustained by the Node.js Foundation, ExpressJS shows many features for making single-page, multi-page, and hybrid web apps. 

ExpressJS

It enables developers to configure Middleware to handle HTTP(HyperText Transfer Protocol) requests, describes routes to perform specific actions based on the HTTP method and URL(Uniform Resource Locator), and supports dynamic rendering of HTML(HyperText Transfer Protocol) pages by passing parameters to templates.

What is Middleware?

Middleware is a request handler that has access to application's request-response cycle. It consists of the response object, request object, and middleware function. We can access and modify the request and response data in Middleware. Suppose you want to block a user or check the authentication; Middleware can do this.

Middleware

Its primary function is to stop the flow of response and request cycle; it can also be called the "next" middleware function to the stack. It alters the req and res objects to perform tasks such as parsing request bodies or adding response headers.

Working On The Middleware Function

A request to an Express application runs through a series of Middleware functions before getting the final route handler. Each middleware function can fulfill precise tasks and modify the request or response objects. These tasks contain authentication, data verification, logging, and error handling.

Working On The Middleware Function

The "next" function is a callback that suggests Express move on to the "next" middleware function. The present middleware function transfers control to the next Middleware in the chain by invoking the "next()" function. If a middleware function does not call the "next()" function, it stops the request at that point, and the client does not receive any other response or processing.

They operate one after another, and each function can choose whether to allow the request to move on to the next Middleware or stop the request from resuming.

Types of Middleware

There are different types of Middleware, such as:

Application-level Middleware

Application-level Middleware is a type of Middleware that affects all other routers in that application. It helps handle tasks like authentication, understanding and processing the requested information, and managing the data sent back in responses.

Router-level Middleware

Router-level middleware applies to specific routes or a group of routes. By enabling the modularization of Middleware, developers can use it for particular parts of an application. Router-level middleware permits more refined control over the flow of requests. You can set the order in which middleware functions need to be executed, and you have the flexibility to use middleware based on specific route requirements conditionally.

Error-handling Middleware

Error-handling Middleware is accountable for detecting and regulating errors during the request-response cycle. Typically, developers define it as the last Middleware in the chain. When an error occurs during the processing of a request, it can be difficult to handle and respond to the error appropriately. Error-handling middleware simplifies this process by letting you define a middleware function that runs when an error occurs.

Built-in Middleware

ExpressJS have various built-in middleware functions like "express.static", "express.json," and "express.urlencoded," which have their roles. The "express.static" middleware function send files like HTML and CSS from a specific folder to users who request them. The "express.json" middleware gathers JSON data from requests, interprets it, and save the resulting JavaScript object to the "req.body" property. The "express.urlencoded" middleware extracts key-value pairs from the request body and saves them as an object in the "req.body" property.

 

Custom Middleware in ExpressJS

In ExpressJS, every middleware function takes three arguments after the request and response objects: reqres, and next

Syntax 

const middleware = function(req, res, next){
   // commands
} 

Parameters

The following are parameters details that are used in Custom Middleware:

Request(req)

The request object (often named req) contains information regarding the incoming HTTP request made by the client.

Response(res)

The response object (often named res) sends the HTTP response to the client. It permits middleware functions to set the response status code, headers, and body content. 

Next(next)

The next function (often named next) is a callback function that passes control to the next middleware function in the chain. By calling next(), the current middleware function signals that it has finished its jobs and wants to give the request to the next middleware function. 

Custom Middleware

Let's create our custom middleware. First, we need to install the necessary modules. You can run the following command in the terminal and easily import all the modules.

npm install Express

We have created an index.js file. In the index.js file, the code sets up a web server using the Express framework in Node.js.The index.js file forms a web server using Express, defines routes, and listens for incoming requests on a particular port. It delivers a base for taking different routes and creating more complicated web applications.

Code

// Requiring necessary modules. 
const express = require('express');

// Created express app object
const app = express();

// Giving the port number.
const port = process.env.PORT || 3000;

// Separator for console logs.
separation = "----------"

// Middleware function to log pageinfo.
const pageInfo = function(req, res, next) {
const Time = new Date().toLocaleString();
const MethodUsed = req.method;
const URLPresentOn = req.url;
const Address = req.socket.remoteAddress;
console.log("pageInfo", Time, separation, MethodUsed, separation, URLPresentOn, separation, Address);
next();
}

// Applying the pageinfo Middleware to all routes.
app.use(pageInfo);

// Root route.
app.get("/", function(req, res) {
res.send("Present at Home Page");
})

// “/code” route
app.get("/code", function(req, res) {
res.send("WELCOME TO CODING NINJA ");
})

// Initializing the server.
app.listen(port, function() {
console.log("server is running", port);
})

To run the index.js file, use the following command. 

node index.js

Output

  • Window output
output
output
  • Terminal output
     
output
output

Explanation

Explanation

This code demonstrates how to construct custom middleware in ExpressJS. 

First, we imported the required 'express' module. The server is created on the port supplied by "process.env.PORT" by the code. 

A middleware function named "pageInfo" is defined, which allows access to the request and response objects and performs operations on them. This middleware function delivers details such as the current time, HTTP method, URL, and remote address. Later, it calls the next() function to control the execution of the next middleware function in the request-response cycle.

The "app. get()" method provides two routes. The first ("/") route is the root route, while the second ("/code") route is associated with the response "WELCOME TO CODING NINJA." 

Call the "app. listen" method to start the server and supply the port number and callback function as inputs.

Advantages of Custom Middleware in ExpressJS

There are many advantages of Custom Middleware in ExpressJS:

  • Developers can manage and maintain the source code more efficiently by using custom middleware, as it breaks the application's logic into smaller and more reusable procedures.
     
  • Middleware's capability to segregate diverse duties, such as authentication, error handling, or logging, results in a more well-organized and manageable code structure.
     
  • You can modify your application's behavior according to particular needs by custom middleware, which enables fine-grained control and customization. 
     
  • The ExpressJS middleware ecosystem is vast, so you may expand the capability of your application by adding new features.

Disadvantages of Custom Middleware in ExpressJS

There are some disadvantages of Custom Middleware in ExpressJS like:

  • As you add additional Middleware to your application, the data flow and the execution sequence of the middleware functions can become more complex.
     
  • Each middleware function affects the application's overall performance, mainly if the Middleware is resource-intensive or not optimized.
     
  • The order in which the middleware functions are declared and run may be critical and require careful attention and testing to ensure the desired functionality and avoid conflicts. 

Frequently Asked Questions

What is Middleware in ExpressJs?

Express.js middleware is a function that works on request and response objects, allowing extra functionality and processing throughout the request-response cycle.

What is the purpose of custom middleware in ExpressJs?

Custom middleware in Express.js performs functions on request and response objects, improves server functionality, and contains different jobs during the request-response cycle.

How to handle errors in custom middleware?

Custom middleware can handle errors by using the next function with an error parameter and specifying an error-handling middleware function with four parameters (err, req, res, next).

Different types of Middleware?

Middleware comes in different forms: application-level Middleware, router-level Middleware, error handling, and built-in Middleware.

What will happen if we don't include the "next" command?

If a middleware function skips the "next" command, it will generate a timeout, as the cycle won't proceed to the next Middleware.

Conclusion

We come across what ExpressJs is and what Middleware is and how it works in detail in this article. We also learned different types of Middleware. We discuss Custom Middleware in ExpressJS in this article. We also saw the syntax and parameters required to create a custom middleware in ExpressJS. With the help of implementing the code, we learned how custom middleware in ExpressJS is made and worked. We also discussed the advantages and disadvantages of custom middleware in ExpressJS.

Do check out the link to learn more about such topic

You can find more informative articles or blogs on our platform. You can also practice more coding problems and prepare for interview questions from well-known companies on your platform, Coding Ninjas Studio.

Live masterclass