Home » Nodejs » The consequences of not calling next() in restify

The consequences of not calling next() in restify

Posted by: admin November 29, 2017 Leave a comment

Questions:

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.

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].

Questions:
Answers:

Another issue (currently) is that the Server after event is not emitted if all handlers don’t call next. For example, if you are using auditLogger to log requests using the after event, you won’t get logs for any requests that reach a handler that doesn’t call next.

I have opened a PR to fix the issue so that the after event is emitted either way, but calling next is the expected norm for apps using restify.