Episode 20 of 21
Logging Users Out
Implement a complete logout flow — clear the session, destroy the cookie, and redirect the user back to the home page.
Logging Users Out
Logging out means destroying the session and redirecting the user. Passport provides a simple method for this.
The Logout Route
// routes/auth-routes.js
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
req.logout() is added to the request object by Passport. It removes the req.user property and clears the session data from the cookie.
What Happens During Logout
1. User clicks "Logout" link (/auth/logout)
2. req.logout() is called
3. Session data is cleared from the cookie
4. req.user becomes undefined
5. User is redirected to the home page
6. Navbar shows "Login with Google" instead of "Logout"
Verifying Logout
// Before logout:
req.user = { username: 'Shaun', googleId: '123...', thumbnail: '...' }
// After logout:
req.user = undefined
Preventing Access After Logout
// Auth guard middleware
function authCheck(req, res, next) {
if (!req.user) {
res.redirect('/');
} else {
next();
}
}
// After logout, visiting /profile redirects to home
router.get('/', authCheck, function(req, res) {
res.render('profile', { user: req.user });
});
Key Takeaways
req.logout()clears the session and removesreq.user- Always redirect after logout — do not leave the user on a blank page
- Auth guard middleware preventing access to protected pages after logout
- The navbar conditionally shows login/logout based on
req.user