Redirecting Users
Redirect users to the right pages — send them to the profile page after login and back to the home page after logout.
Redirecting Users
Right now, after login the user sees a plain text message. Let us redirect them to a profile page after login and back to the home page after logout.
Redirect After Login
// routes/auth-routes.js
router.get('/google/redirect', passport.authenticate('google'),
function(req, res) {
// Instead of res.send(), redirect to profile
res.redirect('/profile');
}
);
Redirect After Logout
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
req.logout() is provided by Passport. It removes the user from the session and clears the cookie. Then we redirect to the home page.
Profile Routes
// routes/profile-routes.js
const router = require('express').Router();
router.get('/', function(req, res) {
res.render('profile', { user: req.user });
});
module.exports = router;
Registering Profile Routes
// app.js
const profileRoutes = require('./routes/profile-routes');
app.use('/profile', profileRoutes);
Protecting Routes (Auth Guard)
// Middleware to check if user is logged in
function authCheck(req, res, next) {
if (!req.user) {
res.redirect('/auth/login');
} else {
next();
}
}
// Apply to profile routes
router.get('/', authCheck, function(req, res) {
res.render('profile', { user: req.user });
});
The authCheck middleware runs before the route handler. If req.user does not exist (user not logged in), it redirects to the login page instead of rendering the profile.
Key Takeaways
res.redirect('/profile')sends the user to the profile page after loginreq.logout()clears the session; redirect to home page after- Use auth guard middleware to protect routes that require login
- Check
req.userto determine if the user is authenticated