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


Scenario: Consider the following is the part of code from a node web app.

app.get('/users/:id?', function(req, res, next){
    var id = req.params.id;
    if (id) {
        // do something
    } else {
        next(); //or return next();

Issue: I am checking which one to go with just next() or return next(). Above sample code works exactly the same for both & did not show any difference in execution.

Question: Can some one put light on this, when to use next() and when to use return next() and some important difference?


Some people always write return next() is to ensure that the execution stops after triggering the callback.

If you don’t do it, you risk triggering the callback a second time later, which usually has devastating results. Your code is fine as it is, but I would rewrite it as:

app.get('/users/:id?', function(req, res, next){
    var id = req.params.id;

        return next();

    // do something

It saves me an indentation level, and when I read the code again later, I’m sure there is no way next is called twice.

Answered By – Laurent Perrin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published