Open In App
Related Articles

What is Middleware in Express.js ?

Improve Article
Save Article
Like Article

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.


const express = require("express");
const app = express();
const port = process.env.port || 3000;
app.get("/", (req, res) => {
    <h2>Welcome to GeeksforGeeks</h2>
    <h5>Tutorial on Middleware</h5>
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


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



  (req, res, next) => {
  (req, res) => {
    <h2>Welcome to GeeksforGeeks</h2>
    <h5>Tutorial on Middleware</h5>



Last Updated : 09 Oct, 2021
Like Article
Save Article
Similar Reads
Related Tutorials