Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if I omit next() in express.js?

The express.js docs state that if next() is never called in route then

the request will be left hanging

(https://expressjs.com/en/guide/writing-middleware.html)

What does it imply? Does it mean that I should finalize every request with next() even if I've already called res.send and the request handling is finished? Won't there be memory leaks or other problems if I do omit it?

Update: I have indeed confused middleware with routes. And I forgot that the cycle can be ended. But I was not sure how to end it.

like image 480
Gherman Avatar asked Oct 10 '17 12:10

Gherman


2 Answers

What does it imply?

It means the request/response cycle is still not finished. The response will not be sent to the browser and the browser will keep waiting.

Does it mean that I should finalize every request with next() even if I've already called res.send and the request handling is finished?

The whole sentence is...

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.

So if you intend to end the cycle within the current middleware you can just call res.send, res.end or res.json without next(). But if you intend to go to the next middleware, you should call next() otherwise it won't go to the next middleware.

Won't there be memory leaks or other problems if I do omit it?

If the request/response cycle is not finished, then the memory allocated to serve that cycle will not be returned, which means memory leaks.

like image 186
Anurat Chapanond Avatar answered Sep 30 '22 12:09

Anurat Chapanond


No memory leak, and you do not want to call next() if there is no more middleware to run(after res.send()). next() is a placeholder for a cb function. That is what middleware is, one or more functions called sequentially, until reaching the end of the request-response cycle.In this example, when we hit the login endpoint we will run 2 pieces of middleware: validate and changeStuff, then we call the returnResponse function and that ends the request-response cycle.

get('/login',
validate,
changeStuff,
returnResponse
);

function validate(req, res, next) {
//validate logic does something then calls next()

next()
//just like calling changeStuff(req, res, next)
}

function changeStuff(req, res, next) {
//changeStuff logic changes something then calls next()

next()
//just like calling returnResponse(req, res, next)
}

function returnResponse(req, res) {
//will return something and that is the end of the req-res cycle
//there are no more functions to call, if you try to call next()
//you would get an error, because at this point next() would be 
//undefined

res.send(req.body)
}
like image 42
Jay Hamilton Avatar answered Sep 30 '22 12:09

Jay Hamilton