Restify Middleware - correctly calling next middleware in stack
Asked Answered
A

1

11

I am using Restify with Nodejs and I have a question on the correct way of returning control to the next middleware in stack. I hope I am using the correct phrase when I say "next middleware in stack".

Basically, my code looks like this:

//server is the server created using Restify
server.use(function (req, res, next) {
    //if some checks are a success
    return next();
});

Now, what I wish to know is should the code be return next(); or should it be just next(); to pass control to the next in stack?

I checked and both work - that is both pieces of code will successfully pass control and return the data as expected - what I wish to know is if there is a difference between the two and if I need to use one over another.

Attalie answered 14/5, 2013 at 13:18 Comment(0)
R
18

There's no difference. I took a look at the Restify source, and it doesn't seem to do anything with the return value of a middleware at all.

The reason for using return next() is purely a matter of convenience:

// using this...
if (someCondition) {
  return next();
}
res.send(...);

// instead of...
if (someCondition) {
  next();
} else {
  res.send(...);
};

It might help prevent errors like this:

if (someCondition) 
  next();
res.send(...); // !!! oops! we already called the next middleware *and* we're 
               //     sending a response ourselves!
Reinhart answered 14/5, 2013 at 13:36 Comment(2)
Hi, can you answer me to What doing next callback in http handlers? server.get('/', function(req,res,next){res.end();}) Should I to call next too?Discomfit
@Discomfit if you don't end the request by sending back a response one way or the other, you can use next() to pass control to the next route/middleware/(error-)handlerReinhart

© 2022 - 2024 — McMap. All rights reserved.