Search code examples
node.jsexpresspassport.jsfacebook-authentication

Redirect the user to origin URL after Facebook login using PassportJS


I have setup Facebook authentication with PassportJS but I'm having trouble redirecting the user back to their original URL.

These are the routes:

  app.get("/api/auth/facebook", passport.authenticate("facebook", { scope: ["public_profile", "email"] }));

  app.get(
    "/api/auth/facebook/callback",
    passport.authenticate("facebook", { failureRedirect: "/login" }),
    (req, res) => {
      logger.debug("Successful authentication");
      res.redirect("/");
    }
  );

I'll omit the Strategy code here because I'm not sure it's relevant, but it's pretty boilerplate, nothing different.

My question is how can I access the original URL on the callback so not to redirect the user back to "/"? A query string param seems to get lost once the request goes to Facebook and back.

Thanks


Solution

  • What I've done to solve this question was to store the user's origin path into the session and redirect they back to it once authentication is complete.

    I added a middleware called storeRedirectToInSession before calling the passport authenticate method, like so:

      app.get(
        "/api/auth/facebook",
        storeRedirectToInSession,
        passport.authenticate("facebook", { scope: ["public_profile", "email"] })
      );
    
      app.get(
        "/api/auth/facebook/callback",
        passport.authenticate("facebook", { failureRedirect: "/login" }),
        (req, res) => {
          logger.debug("Successful authentication");
          res.redirect(req.session.redirectTo);
        }
      );
    

    The middleware:

    const storeRedirectToInSession = (req, res, next) => {
      let url_parts = url.parse(req.get("referer"));
      const redirectTo = url_parts.pathname;
      req.session.redirectTo = redirectTo;
      next();
    };
    

    This requires the 'url' node package. I'm also using express and express-session packages.