The Wayback Machine - https://web.archive.org/web/20240828110831/https://www.geeksforgeeks.org/what-is-middleware-in-express-js/
Open In App

What is Middleware in Express.js ?

Last Updated : 09 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle.

Middlewares are used for:

  • Change the request or response object.
  • Execute any program or code
  • End the request-response lifecycle
  • Call the next middleware.

The next() function is used to call the next middleware, succeeding the current middleware. It is very important to note that the middleware should either stop the current lifecycle or pass it on to the next middleware, otherwise the webpage will keep loading.

Middleware Syntax: The basic syntax for the middleware functions are as follows –

app.get(path, (req, res, next) => {}, (req, res) => {})

The middle part (req,res,next)=>{} is the middleware function. Here we generally perform the actions required before the user is allowed to view the webpage or call the data and many other functions. So let us create our own middleware and see its uses.

Let us create our middleware and see that how it executes.

Step 1: Go to your project directory and enter the following command to create a NodeJs project. Make sure that NodeJs is installed in your machine.

npm init -y

It will create a package.json file. 

Step 2: Install two dependencies using the following command.

npm install express nodemon

Step 3: In the scripts section of the package.json file, add the following code line.

"start": "nodemon index.js", 

Step 4: Create an index.js file in the directory. Make sure that it is not inside any subdirectories of the directory you are working in.

Project Structure: It will look like the following. 

Project Structure

Now we will set up our express app and send a response to our server.

Here is the code for the index.js file.

Javascript




const express = require("express");
const app = express();
  
const port = process.env.port || 3000;
app.get("/", (req, res) => {
  res.send(`<div>
    <h2>Welcome to GeeksforGeeks</h2>
    <h5>Tutorial on Middleware</h5>
  </div>`);
});
app.listen(port, () => {
  console.log(`Listening to port ${port}`);
});


Step to run the application: Run the code by entering the following command on the terminal.

npm start

Output:

Create a Middleware: In the app.get() function, modify according to the following code.

index.js

Javascript




app.get(
  "/",
  (req, res, next) => {
    console.log("hello");
    next();
  },
  (req, res) => {
    res.send(`<div>
    <h2>Welcome to GeeksforGeeks</h2>
    <h5>Tutorial on Middleware</h5>
  </div>`);
  }
);


Output:

Middleware



Similar Reads

Purpose of the express.Router middleware in Express
express.Router() in ExpressJS is like creating a mini-app within your main app. It helps organize routes and related functionalities, making it easier to manage different parts of your web application separately. express.Router() acts as a path organizer in ExpressJS, helping to structure and manage routes efficiently within a web application. Purp
1 min read
Explain the purpose of the express.static middleware in Express JS
The express.static middleware in ExpressJS simplifies serving static files like HTML, CSS, and images, improving performance and enhancing user experience in web applications. Purpose of the express.static middleware in ExpressJS:Serves Static Files: express.static middleware serves static files like HTML, CSS, JavaScript, and images from a specifi
2 min read
What is the purpose of the express-validator middleware in Express JS?
The express-validator middleware is a powerful tool for validating and sanitizing incoming request data in ExpressJS applications. It helps ensure that user input meets specified criteria, preventing security vulnerabilities and data corruption. With built-in error handling and customizable rules, express-validator seamlessly integrates with Expres
2 min read
What is express-session middleware in Express?
In the Express web application, the express-session middleware is mainly used for managing the sessions for the user-specific data. In this article, we will see the use of express-session middleware for session management in Express with practical implementation. PrerequisitesNode JSExpress JSTable of Content What is express-session Middleware?Step
2 min read
Middleware in NestJS: Implementing Custom Middleware for Request Processing.
Middleware in NestJS plays an important role in intercepting and processing HTTP requests before they reach route handlers. It allows developers to execute code logic before or after handling a request, making it a powerful tool for managing cross-cutting concerns such as logging, authentication, error handling, and more. In this article, we will e
3 min read
Working of Express.js middleware and its benefits
Framework: It is known to be a skeleton where the application defines the content of the operation by filling out the skeleton. For Web development, there is python with Django, java with spring, and For Web development in we have Node.js with Express.js in node.js there is an HTTP module by which we can create only limited operatable websites or w
7 min read
How to pass variables to the next middleware using next() in Express.js ?
The following example covers how to pass variables to the next middleware using next() in Express.js. Approach: We cannot directly pass data to the next middleware, but we can send data through the request object. [Middleware 1] [Middleware 2] request.mydata = someData; -------&gt; let dataFromMiddleware1 = request.mydata; Installation of Express m
2 min read
How to create custom middleware in express ?
Express.js is the most powerful framework of the node.js. Express.js is a routing and Middleware framework for handling the different routing of the webpage, and it works between the request and response cycle. Express.js use different kinds of middleware functions in order to complete the different requests made by the client for e.g. client can m
2 min read
How to skip a middleware in Express.js ?
If we want to skip a middleware we can pass parameters to the middleware function and decide based on that parameter which middleware to call and which middleware to not call. Prerequisite: express.js: To handle routing. Setting up environment and execution: Step 1: Initialize node project npm init Step 2: Install required modules npm install expre
1 min read
Express Error Handling - Middleware for Production and Development
Error handling is the process of detecting and responding to errors that occur during the execution of a program or application. In the context of web applications, error handling typically involves detecting errors that occur during the handling of HTTP requests and responding appropriately to those errors. Effective error handling is important be
4 min read
Difference between app-level and route-level middleware in Express
Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next middleware function in the application's request-response cycle. In this article, we will go through app-level and route-level middleware and also see the key differences between them. Table of Content What is App-level Middl
3 min read
Difference between application level and router level middleware in Express?
If you’ve used Express even a little, you know how important middleware is. Those little functions run on every request and let you do stuff like logging, authentication, file uploads, and more. In this article, we will see what is Application-level middleware and Router-level middleware and what are the key differences between them. Table of Conte
3 min read
Purpose of middleware in Express
Middleware in Express is like a set of tools or helpers that helps in managing the process when your web server gets a request and sends a response. Mainly it's work is to make the Express framework more powerful and flexible. It allows users to insert additional steps or actions in the process of handling a request and generating a response. It's
2 min read
Purpose of body-parser Middleware in Express
Express middleware acts like a toolbox for your web server, enabling you to customize how it manages requests and responses. It's a handy set of tools, that enhances Express's flexibility for specific tasks and gives you control over your server's capabilities Purpose of the body-parser Middleware in Express:Data Handling: body-parser is a middlewa
1 min read
What is the purpose of the cookie-parser middleware in Express.js?
cookie-parser is middleware that simplifies handling cookies. It parses incoming cookies from client requests and makes them accessible in the req.cookies object. This makes it easier to read and manipulate cookies in your Express JS application without manual parsing. Purpose of the cookie-parser middleware in ExpressJS:Cookie Parsing: Automatical
2 min read
Explain the purpose of the helmet middleware in Express JS
Helmet is a security middleware for ExpressJS applications. It helps protect your web application from common security vulnerabilities by setting HTTP headers that enhance security. By using Helmet, you can easily add an extra layer of protection to your ExpressJS application without needing to manually configure each security header. Purpose of th
2 min read
What is the purpose of the compression middleware in Express JS ?
Middleware in Express JS is like a set of tools or helpers that helps in managing the process when your web server gets a request and sends a response. Mainly it’s work is to make the ExpressJS framework more powerful and flexible. It allows users to insert additional steps or actions in the process of handling a request and generating a response.
2 min read
What is the purpose of the morgan middleware in Express.js?
Morgan is a widely used middleware for logging HTTP requests. It simplifies the process of logging HTTP requests in your application by automatically capturing request information such as request method, URL, status code, response time, and more. Morgan logs this information to the console or a specified log file, making it useful for debugging, mo
2 min read
How to get url after "#" in Express Middleware Request ?
In Express, the fragment identifier (the part of the URL after the # symbol) is not directly accessible on the server side because it is not sent to the server as part of the HTTP request. The fragment identifier is typically used for client-side navigation and is processed on the client side only. If we need to access data from the fragment identi
3 min read
What is the role of next(err) in error handling middleware in Express JS?
Express is the most popular framework for Node.js which is used to build web-based applications and APIs. In application development, error handling is one of the important concepts that provides the aspect to handle the errors that occur in the middleware. The middleware functions have access to the request object, the response object, and the nex
4 min read
How to create Custom Error Handler middleware in Express ?
Error handling is one of the crucial part while building applications. In Express JS middleware functions can be used to handle errors effectively. In this article, we will learn How to create custom error-handling middleware in Express. Prerequisites:Node JSExpress JSApproach to create Custom Error Handler:The first middleware simulates an error b
3 min read
How to use third-party middleware in Express JS?
Express JS is a robust web application framework of Node JS which has the capabilities to build web and mobile applications. Middleware is the integral part of the framework. By using the third party middleware we can add additional features in our application. PrerequisitesNode JSExpress JSPostmanTable of Content What is Third-Party Middleware?Ste
2 min read
What is middleware chaining in Express JS, and how is it useful?
In Express JS there is the process of Middleware chaining by which multiple middleware functions sequentially can be processed and also can be able to modify the incoming requests before they reach the final route handler. In this article, we will see the concept of Middleware Chaining in Express JS with a proper example demonstration. Prerequisite
4 min read
Built-in Middleware Functions in Express.js
Express.js is a Node.js framework used to develop the backend of web applications. While you can create custom middleware in Express.js using JavaScript, Express.js also provides several built-in middleware functions for use in Express applications. Middleware are functions that are executed when called and then pass control to the next middleware
4 min read
Middleware in Express
Express serves as a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle. Middleware gets executed after the server receives the request and before the controller actions send the response. Middleware has and access to the request object, responses object, and next, i
5 min read
Express.js express.text() Function
The express.text() function is a built-in middleware function in Express. It parses the incoming request payloads into a string and is based on body-parser. Syntax: express.text( [options] ) Parameter: The options parameter contains various properties like defaultCharset, inflate, limit, verify, etc. Return Value: It returns an Object. Installation
2 min read
Express.js express.raw() Function
The express.raw() function is a built-in middleware function in Express. It parses incoming request payloads into a Buffer and is based on body-parser. Syntax: express.raw( [options] ) Parameter: The options parameter contains various properties like inflate, limit, type, etc. Return Value: It returns an Object. Installation of the express module:
2 min read
Express.js express() function Complete Reference
Express.js is a small framework that works on top of Node.js web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. Express.js express() Methods:Method Description Express.js express.json() Function The express.json() function is a buil
1 min read
Express express.Router() Function
The express.Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.  Syntax: express.Router( [options] )Optional Parameters: case-sensitive: This enables case sensitivity.mergeParams: It preserves the req.params values from the parent router.stric
2 min read
Express express.urlencoded() Function
The express.urlencoded() function is a built-in middleware function in Express. It parses incoming requests with URL-encoded payloads and is based on a body parser. Syntax:  express.urlencoded( [options] )Parameter: The options parameter contains various properties like extended, inflate, limit, verify, etc. Return Value: It returns an Object. Step
2 min read