The consequences of not calling next() in restify
Asked Answered
L

2

14

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.

Lampoon answered 12/3, 2014 at 14:37 Comment(0)
C
23

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

Countrybred answered 17/3, 2014 at 6:23 Comment(3)
Makes sense. So, next() is handling the sequence of how routes are being processed? All routes will still be processed but perhaps not in the order indicated in the script?Lampoon
@Stockholmux The routes will still be processed in the right order with respect to each other. However, any route that uses a handler that does not call next() may not be completely processed. Every route has its own handler chain. For example, whenever you call restify.use(), you are incrementally adding a handler to the chains of every route. And the handlers are added in the order that they are defined at runtime by your code. So, no handler can be sure that it will always be the last one called in every route in which it is used.Countrybred
Ah - that makes sense, especially with the .use() - I had not considered the middlewear angle.Lampoon
D
5

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.

Dollhouse answered 10/2, 2016 at 16:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.