I'm trying to write middleware for authentication. And I want this if statement to redirect the user to '/'
if they're not logged in. If they're logged in, I wan't to redirect them to '/news'.
/*Simplified for this example*/
if(rs.authenticated === true) {
next();
} else {
res.redirect('/');
}
Is there a way to do this inside of these if statements? Or do I have to write a new method? I've tried several ways with if statements but I just get redirect loops.
I'm trying to write middleware for authentication. And I want this if statement to redirect the user to '/'
if they're not logged in. If they're logged in, I wan't to redirect them to '/news'.
/*Simplified for this example*/
if(rs.authenticated === true) {
next();
} else {
res.redirect('/');
}
Is there a way to do this inside of these if statements? Or do I have to write a new method? I've tried several ways with if statements but I just get redirect loops.
Share Improve this question asked Jun 25, 2013 at 20:41 georgesampergeorgesamper 5,1795 gold badges44 silver badges60 bronze badges2 Answers
Reset to default 6The standard pattern would be for all pages requiring a logged-in user to use a middleware that verifies a logged-in user and redirects to /
if they are not logged in.
function loggedIn(req, res, next) {
if(req.authenticated === true) {
next();
} else {
res.redirect('/');
}
}
app.get('/news', loggedIn, newsRoute);
app.get('/', homeRoute);
Your problem is you are using a middleware for all routes, when you really only want to use it for protected routes, which is where your redirect loop is happening. If you want to send logged-in users to '/news' instead of '/', you can either just render the right template or do a conditional redirect in there.
function homeRoute(req, res) {
if (req.authenticated) {
return res.redirect('/news');
}
res.render('home');
}
You want to introduce a small middleware for checking if the user is logged in. You set it up on a route handler level.
Please see those SO answers:
javascript node.js next()
How does Express/Connect middleware work?
What is the parameter "next" used for in Express?