How to redirect to previous page after authentication in Node.js using Passport.js?

Sometimes, we want to redirect to previous page after authentication in Node.js using Passport.js.

In this article, we’ll look at how to redirect to previous page after authentication in Node.js using Passport.js.

How to redirect to previous page after authentication in Node.js using Passport.js?

To redirect to previous page after authentication in Node.js using Passport.js, we can use our own middleware to do the redirect depending on authentication status.

For instance, we write

const restrict = (req, res, next) => {
  if (!req.session.userId) {
    req.session.redirectTo = '/account';
    res.redirect('/login');
  } else {
    next();
  }
};

app.get('/auth/return', restrict, (req, res) => {
  const redirectTo = req.session.redirectTo || '/';
  delete req.session.redirectTo;
  res.redirect(redirectTo);
});

to define the restrict middleware function that checks if req.session.userId is defined.

If it is, then the user is authenticated and we call next to call the next middleware which does the redirect.

Otherwise, we set req.session.redirectTo to '/account' and call res.redirect to redirect the user to '/login'.

In the /auth/return route handler middleware, we remove the req.session.redirectTo property with delete.

And then we do the redirect with res.redirect to the redirectTo path.

Conclusion

To redirect to previous page after authentication in Node.js using Passport.js, we can use our own middleware to do the redirect depending on authentication status.