0

I have API to deal with post request as follow(simplified):

myFunc(req: express.Request, res: express.Response, next){
    let err = 'err detected!';
    //validateSometing() returns a boolean value, true if validation pass false otherwise
    if(!validateSomething()){
       res.status(500).json(err);
       return next(err);
    }  
    //more code...logic if validation pass
}

I would like to know if return next(err); or return; is required to stop the function flow after sending the status and related err back to client. In other words, does res.status(500).json(err); stops the function flow?

Thanks!

bunny
  • 1,797
  • 8
  • 29
  • 58
  • maybe a duplicate https://stackoverflow.com/questions/16810449/when-to-use-next-and-return-next-in-node-js – AZ_ Feb 06 '19 at 04:07

1 Answers1

0

next() is a middleware function in the application’s request-response cycle. You must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

res.json(), res.send() is a express function used to send response to the client application . In other words it used this functions used to build your HTTP Reponse.

return keyword returns from your function, thus ending its execution. This means that any lines of code after it will not be executed.

Note : Both next() and res.send() will not end your function from execution. Where adding a return will stop function execution after triggering the callback.

Use return is to ensure that the execution stops after triggering the callback. In some circumstances, you may want to use res.send and then do other stuff.

Example :

app.use((req, res, next) => {
  console.log('This is a middleware')
  next()
  console.log('This is first-half middleware')
})

app.use((req, res, next) => {
  console.log('This is second middleware')
  next()
})

app.use((req, res, next) => {
  console.log('This is third middleware')
  next()
})

Your output will be:

This is a middleware
This is second middleware
This is third middleware
This is first-half middleware

That is, it runs the code below next() after all middleware function finished.

However, if you use return next(), it will jump out the callback immediately and the code below return next() in the callback will be unreachable.

Şivā SankĂr
  • 1,966
  • 1
  • 18
  • 34
  • next also is used in error handling. ref https://expressjs.com/en/guide/error-handling.html – AZ_ Feb 06 '19 at 04:03