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:
- 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
const express = require( "express" );
const app = express()
app.use( "/" , (req, res, next) => {
console.log( "Hello" );
})
app.get( "/" , (req, res, next) => {
console.log( "Get Request" )
})
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
const express = require( "express" );
const app = express()
app.use( "/" , (req, res, next) => {
console.log( "Hello" );
next();
})
app.get( "/" , (req, res, next) => {
console.log( "Get Request" )
})
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
Share your thoughts in the comments
Please Login to comment...