Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • path: It is the path for which the middleware function is being called. It can be a string representing a path or path pattern or a regular expression pattern to match the paths.
  • callback: It is the callback function that contains the request object, response object, and next() function to call the next middleware function if the response of the current middleware is not terminated. In the second parameter, we can also pass the function name of the middleware.

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

Javascript




// 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

Javascript




// 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

 



Last Updated : 18 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads