Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to call next() after res.send()?

Tags:

If I called res.send(), but didn't call next():

  1. Any middleware after this middleware won't be executed.
  2. If this middleware is not the last middleware, then the request will "hang" forever, and will not be garbage collected, because It is still waiting for the next() to be called.

The above is my attempt to argue that I should always call next(), is it true?

like image 903
golopot Avatar asked Nov 20 '16 05:11

golopot


People also ask

Do you need to call next () in Express?

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging. An Express application can use the following types of middleware: Application-level middleware.

What does Res send () do?

send() Send a string response in a format other than JSON (XML, CSV, plain text, etc.). This method is used in the underlying implementation of most of the other terminal response methods.

What is next () node?

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.


2 Answers

You don't need to call next() to finish sending the response. res.send() or res.json() should end all writing to the response stream and send the response.

However, you absolutely can call next() if you want to do further processing after the response is sent, just make sure you don't write to the response stream after you call res.send().

like image 72
Alexander Mills Avatar answered Sep 27 '22 16:09

Alexander Mills


Simply

  1. All the middlewares use same request and response objects, so if you send the response via any middleware all next middlewares will be skipped
  2. You can still execute further operations by calling next(); but you can't do res.send() or res.json() further
like image 40
Vaibhav KB Avatar answered Sep 27 '22 17:09

Vaibhav KB