Redirecting client with NodeJS and Restify

Routhinator picture Routhinator · Sep 4, 2013 · Viewed 11.3k times · Source

I'm building a REST backend for an SPA with NodeJS, Restify and PassportJS for authentication. Everything's working except the last step, which is redirecting the client from the backends /login/facebook/callback to the home page of the application.

I've searched online and found lots of answers for ExpressJS but nothing useful for Node-Restify yet. I've managed to pick up a few snippets of code and this is what I'm attempting at the moment:

app.get('/api/v1/login/facebook/cb', passport.authenticate('facebook', { scope: 'email' }), function(req, res) {
    req.session.user = req.user._id;
    res.header('Location', '/#/home');
    res.send();
});

The response is sent but the location header is not included and the client is presented with a white screen. How do I do a proper redirect using the Node-Restify API?

Answer

james_womack picture james_womack · Sep 5, 2015

Restify's Response interface now has a redirect method.

As of this writing, there's a test showing how to use it here.

The contents of that test are:

server.get('/1', function (req, res, next) {
    res.redirect('https://www.foo.com', next);
});

Many folks who use Restify are more familiar with ExpressJS. It's important to understand that (again, as of this writing) one of the three main public API differences affecting porting of Express plugins is that the res.redirect method in Restify requires you to pass next (or an InternalError is thrown). I've personally ported several modules from Express to Restify and the main API differences at first are (in Restify):

  • server.use is only for path & HTTP-method-agnostic middleware
  • res.redirect requires that you pass next
  • Some members or the Request interface are methods rather than values, such as req.path. req.path is an alias of req.getPath in Restify

I am NOT saying that under-the-hood they are similar, but that the above three things are the main obstacles to porting over Express plugins. Under-the-hood, Restify has many advantages over Express in my experience using it in both large enterprise applications and personal projects.