Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The consequences of not calling next() in restify

I've been using Restify for some time now. I ran across some code that lacks next() and it occurred to me that I'm not sure if I fully understand the reason why next() should be called after res.send(). I get why would use it in a middleware situation, but for a normal route why is it needed? For example:

server.get('/a/:something/',function(req,res,next) {
    res.send('ok');
});

vs

server.get('/b/:something/',function(req,res,next) {
    res.send('ok');
    return next();
});

If return next(); is left out of the code it seems to not cause errors and works from what that I can see.

like image 555
stockholmux Avatar asked Mar 12 '14 14:03

stockholmux


People also ask

What is next in restify?

The restify API Guide has this to say: You are responsible for calling next() in order to run the next handler in the chain. The 'chain' they are referring to is the chain of handlers for each route. In general, each route will be processed by multiple handlers, in a specific order.

What is Restify?

Restify is a framework built specifically to build REST web services in Node. js frameworks such as Express. js and Hapi. Restify manages such difficult tasks as versioning, error handling, and content negotiation.


1 Answers

The restify API Guide has this to say:

You are responsible for calling next() in order to run the next handler in the chain.

The 'chain' they are referring to is the chain of handlers for each route. In general, each route will be processed by multiple handlers, in a specific order. The last handler in a chain does not really need to call next() -- but it is not safe to assume that a handler will always be the last one. Failure to call all the handlers in a chain can result in either serious or subtle errors when processing requests.

Therefore, as good programming practice, your handlers should always call next() [with the appropriate arguments].

like image 182
cybersam Avatar answered Sep 19 '22 09:09

cybersam