Open In App

What is Middleware in Express.js ?

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:



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) => {
  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




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


Article Tags :