Skip to content

Express js middleware is not working as expected. It is showing too many redirections

Express js middleware is not working as expected. It is showing too many redirections. When i remove the token or logout it shows in the browser that too many redirections

Middleware

const isAuthenticate = async (req, res, next) => {
  const token = req.cookies.jwt;
if (token) {
    jwt.verify(token, "thisisjwtsecret", async (err, token_decode) => {
      if (!err) {
        const u_id = token_decode._id;
        const userData = await User.findOne({ _id: u_id });
        req.user = userData;
        req.isAuth = true;
        next();
      } else {
        res.redirect("/user/login");
      }
    });
  } else {
    res.redirect("/user/login");
    }
};

Route.js

// Auth Controller
const AuthController = require("../../controllers/auth/AuthController");
const { isAuthenticate } = require("../../middlewares/isAutheticated");

router.get("/user/login", isAuthenticate, AuthController.login);
router.post("/user/login", AuthController.checkLogin);
router.get("/user/register", isAuthenticate, AuthController.createUser);
router.post("/user/register", isAuthenticate, AuthController.storeUser);
module.exports = router;

LOgin function

// Showing Login Page to User
const login = (req, res) => {
  return res.render("auth/login");
};

When i remove the token or logout it shows in the browser that too many redirections

Answer

Now that you’ve shown revised code for isAuthenticate(), the redirect loop is caused by the redirects in that code. Here’s what happens:

Some route you have (any route) that uses isAuthenticate as middleware for the route detects that the user is not logged in. It then redirects to /user/login. That’s fine up to that point. Then, the browser issues a new request for /user/login and that takes you to this route definition:

router.get("/user/login", isAuthenticate, AuthController.login);

But, that route definition again runs the isAuthenticate() middleware which redirects to /user/login and thus you have an infinite redirect loop.

Probably you just need to remove the isAuthenticate() check from this route. If the user is already going to the /user/login page, you don’t need to check their authentication or redirect them. If you have a reason to want to know if they are authenticated or not, then you need a separate version that ONLY does the auth check and does not redirect and you can use that in the /user/login route definition.


Original answer before code was shown that did res.redirect().

So, this middleware you show sets req.isAuth to true or false and then calls next() to continue routing. All three code paths through that middleware just set req.isAuth and then call next(). Nowhere in this middleware does it do any redirect. So, if the core problem is too many redirections, that issue must be caused somewhere else by some other route/middleware that actually does a redirect, probably when it sees that req.isAuth is false since you said that the problem occurs when logged out or when the token is missing.

When redirecting, you have to make absolutely sure that when you redirect to a URL, there is ZERO chance (no code path of any kind) that the route handler for that URL will also redirect to that URL. That’s how you get into a redirect loop.

Looking at the other routes you show, if the too many redirects issue is when redirecting to /user/login, then it seems likely the problem is in the authController.login() handler from this route:

router.get("/user/login", isAuthenticate, AuthController.login);

If the code for that route checks req.isAuth and redirects in any circumstances, then that would be an endless redirect loop.

If you need further advice, please provide the following information:

  1. Which exact redirect URL is causing the problem of too many redirects? Is is /user/login?
  2. Show us the code for the route that does that redirect because that’s apparently where the fault is.