Open In App

What is the use of next() function in Express.js ?

Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client’s different incoming requests. In this article, we will discuss, the use of the next() function in every middleware of the express.js.

There are lots of middleware functions in Express.js like the Express.js app.use() function, and many more. The app.use() middleware is basically used to define the handler of the particular request made by the client.



Syntax:

app.use(path,(req,res,next))

Parameters: It accepts the two parameters as mentioned above and described below:



Installing Module: Install the express module using the following command.

npm install express

Project structure: It will look like this.

Example 1: Server without next() function

Filename: index.js




// Importing the express module
const express = require("express");
const app = express()
 
// Creating First Middleware
app.use("/", (req, res, next) => {
    console.log("Hello");
    // There is no next() function calls here
})
 
// Creating second middleware
app.get("/", (req, res, next) => {
    console.log("Get Request")
})
 
// Execution the server
app.listen(3000, () => {
    console.log("Server is Running")
})

Run index.js file using below command:

node index.js

Output: Without the next() function the middleware doesn’t call the next middleware even they request a path of the same

Server is Running
Hello

Example 2: Server with next() function

Filename: index.js




// Importing the express module
const express = require("express");
const app = express()
 
// Creating First Middleware
app.use("/", (req, res, next) => {
    console.log("Hello");
    // The next() function called
    next();
})
 
// Creating second middleware
app.get("/", (req, res, next) => {
    console.log("Get Request")
})
 
// Execution the server
app.listen(3000, () => {
    console.log("Server is Running")
})

Run index.js file using the below command:

node index.js

Output:

Server is Running
Hello
Get Request

 


Article Tags :