Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js ERR_TOO_MANY_REDIRECTS error

Here's the scenario.

If a user wants to see a page that requires user access, I want to redirect him to the homepage, but I get ERR_TOO_MANY_REDIRECTS error when I try to access the homepage.

I couldn't figure it out how to solve this.

app.js

exports.ensureAuthenticated = function (req, res, next) {
    jwt.verify(req.cookies.userToken, "NICETRY", function (err, decoded) {
        if (err) {
            res.redirect("http://localhost:4000");
        } else {
            // no err
            if (decoded.id) {
                req.id = decoded.id;
                req.iat = decoded.iat;
                next();
            } else {
                res.send("invalid cookie");
            }
        }
    });
};

routes/frontend/index.js

var express = require('express');
var router = express.Router();

var indexController = require('../../controllers/frontend/indexController');
var auth = require('../../app').ensureAuthenticated;

router.get('/', auth, indexController.index);

module.exports = router;

indexController.js

exports.index = function (req, res) {
    res.render('frontend/home/index');
};
like image 269
salep Avatar asked Apr 09 '26 20:04

salep


1 Answers

The issue is that you're redirecting back to the same page once authentication fails and so your ensureAuthenticated middleware runs again and redirects again.

Try making one authenticated route and one unauthenticated route.

router.get('/', indexController.index);  // no auth necessary
router.get('/private', auth, indexController.private); // requires auth

Now if you fail auth when you visit /private it will redirect to / which will display to the unauthenticated user.

like image 64
Alex Brandes Avatar answered Apr 12 '26 08:04

Alex Brandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!