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.
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
Run index.js file using below command:
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
Run index.js file using the below command:
Server is Running Hello Get Request