Open In App

When to use next() and return next() in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this is article we will see when to use next() and return next() in NodeJS.

Features:

  • next() : It will run or execute the code after all the middleware function is finished.
  • return next() : By using return next it will jump out the callback immediately and the code below return next() will be unreachable.

Syntax:

next()
return next()
app.use((req, res, next) => {
//next() or return next()
});

In the function app.use((req, res, next), we have three callbacks i.e. request, response and next.

So, if you want to use next() then simply write next() and if you want to use return next then simply write return next().

Let’s understand these two by an example.

Using next(): If you have any middleware function and below the next() you have some lines or function that you want to execute, then by using next() you can actually execute the lines or function because it runs the code below next() after all middleware function finished.

Using return next(): If you have any middleware function and below the return next() you have some lines that you want to execute, then the lines which are below return next() won’t be executed because it will jump out the callback immediately and the code below return next() in the callback will be unreachable. 

Example: Setting up the environment

npm init -y
    Installing dependencies
npm install express

Javascript




import express from "express"
  
const app = express()
// API for the testing of next() 
app.get(
  '/next', function (req,res,next) { 
    console.log('hi there ');
    next();
    console.log('you are still here');
  }
)
  
// API for the testing of return next() 
app.get(
  '/return-next', function (req,res,next) { 
    console.log('hi there');
    return next(); 
    console.log('you are still here');
  }
)
  
app.listen(5000,()=> {
  console.log("App is running on port 5000")
})


Output :

  1. next(): Hit ‘http://localhost:5000/next’ in your browser.

    Here the line which is below the next() is executed successfully and “you are still here” is shown in the output.

  2. return next(): Hit ‘http://localhost:5000/return-next’ in your browser.

    Here the line which is below the return next() is not executed and “you are still here” is not shown in the output.



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