Search code examples
node.jsexpressherokuhandlebars.js

Redirected you too many times error after hosting on Heroku


I just hosted my Node.js application on Heroku. I use Handlebars templating for the front end. After logging in, I was supposed to be redirected to my dashboard but instead, I got the following error,

fyngram-dev.herokuapp.com redirected you too many times.

Everything works on my local server but doesn't go past user login in production.

I've tried the solutions I've found online and none of them has worked so far.

But my main question is how do I know exactly what is the cause of the redirection error so that I can know exactly what solution to apply?

These are the routes of interest at this point

Get Sign in Page

let authorization;

router.get("/admin/signin", async (req, res) => {
  if (!authorization) {
    return res.render("signin", { title: "Admin Signin" });
  } else {
    return res.redirect("/dashboard");
  }
});

Sign In

router.post("/admin/signin", async (req, res) => {
  try {
    // check if user exists with username
    const checkUsername = await User.findOne({
      username: req.body.key,
      userType: "admin",
    });

    if (!checkUsername) {
      // if username doesn't exist, check if email exists
      const checkEmail = await User.findOne({
        email: req.body.key,
        userType: "admin",
      });

      if (!checkEmail) {
        // if email doesn;t exist, return error message

        return res.render("signin", {
          message: "User doesn't exist.",
          messageClass: "alert-danger",
          title: "Admin Signin",
        });

      } else {
        // if email exists, check if password is correct
        const isMatch = await bcrypt.compare(
          req.body.password,
          checkEmail.password
        );

        if (!isMatch) {
          return res.render("signin", {
            message: "Incorrect email, username or password",
            messageClass: "alert-danger",
            title: "Admin Signin",
          });

        } else {
          // if login with email works, generate auth token and return user
          const token = await checkEmail.generateAuthToken();

          req.headers.authorization = `Bearer ${token}`;

          authorization = req.headers.authorization;

          return res.redirect("/dashboard");
        }
      }
    } else {
      // if username exists, check if password is correct
      const isMatch = await bcrypt.compare(
        req.body.password,
        checkUsername.password
      );

      if (!isMatch) {
        return res.render("signin", {
          message: "Incorrect email, username or password",
          messageClass: "alert-danger",
          title: "Admin Signin",
        });
      } else {
        // if password is correct, generate auth token and return user
        const token = await checkUsername.generateAuthToken();

        req.headers.authorization = `Bearer ${token}`;

        authorization = req.headers.authorization;

        return res.redirect("/dashboard");
      }
    }
  } catch (e) {
    return res.render("signin", {
      message: "Invalid Credentials",
      messageClass: "alert-danger",
      title: "Admin Signin",
    });
  }
});

Get Dashboard Page

router.get("/dashboard", async (req, res) => {
    try {
      const token = authorization.replace("Bearer ", "");

      const decoded = jwt.verify(token, process.env.JWT_SECRET);

      const loggedInUser = await User.findOne({
        _id: decoded._id,
        "tokens.token": token,
        userType: "admin",
      }).lean();

      if (!loggedInUser) {
        return res.redirect("/admin/signin");
      } else {
        ...
        return res.render("dashboard", {
          loggedInUser,
          title: "Dashboard",
        });
      }
    } catch (e) {
      return res.redirect("/admin/signin");
    }
});

Any help to point me in the right direction will be appreciated


Solution

  • After debugging my application carefully, I found out the problem wasn't from my Heroku deployment. Instead, it was from my application logic. I was checking for a dynamic value that could be undefined. (My bad). I added a default value to prevent the error ever again.