Session-based authentication helps keep users logged in by remembering them on the server. It stores user info safely between requests.
Session-based auth with express-session
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Express
const session = require('express-session'); app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: false, cookie: { secure: false } }));
secret is a string used to sign the session ID cookie. Keep it safe.
resave false means don't save session if nothing changed.
Examples
Express
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));Express
app.use(session({
secret: 'mySecret',
cookie: { secure: true }
}));Sample Program
This example shows a simple Express app using express-session to handle login, protect a dashboard page, and logout. User info is stored in the session.
Express
const express = require('express'); const session = require('express-session'); const app = express(); app.use(express.urlencoded({ extended: true })); app.use(session({ secret: 'simpleSecret', resave: false, saveUninitialized: false, cookie: { secure: false } })); // Simple user database const users = { user1: 'pass1', user2: 'pass2' }; // Login form app.get('/login', (req, res) => { res.send(`<form method='POST' action='/login'> <input name='username' placeholder='Username' required /> <input name='password' type='password' placeholder='Password' required /> <button type='submit'>Login</button> </form>`); }); // Handle login app.post('/login', (req, res) => { const { username, password } = req.body; if (users[username] && users[username] === password) { req.session.user = username; res.send(`Welcome, ${username}! <a href='/dashboard'>Go to Dashboard</a>`); } else { res.send('Invalid login. <a href="/login">Try again</a>'); } }); // Protected dashboard app.get('/dashboard', (req, res) => { if (req.session.user) { res.send(`Hello ${req.session.user}, this is your dashboard. <a href='/logout'>Logout</a>`); } else { res.send('Please <a href="/login">login</a> first.'); } }); // Logout app.get('/logout', (req, res) => { req.session.destroy(err => { if (err) { return res.send('Error logging out'); } res.send('Logged out. <a href="/login">Login again</a>'); }); }); app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Important Notes
Always keep your session secret private and strong.
Set cookie.secure to true only if your site uses HTTPS.
Sessions store data on the server, so they are safer than storing info in cookies.
Summary
Session-based auth keeps users logged in by storing info on the server.
Use express-session middleware to manage sessions easily.
Protect routes by checking if session user info exists.
Practice
1. What is the main purpose of using
express-session in an Express app?easy
Solution
Step 1: Understand session purpose
Sessions store user info on the server to remember users between requests.Step 2: Identify express-session role
Theexpress-sessionmiddleware manages these sessions automatically.Final Answer:
To store user data on the server and keep users logged in across requests -> Option AQuick Check:
Session-based auth = store user data server-side [OK]
Hint: Sessions keep user info server-side to maintain login [OK]
Common Mistakes:
- Confusing sessions with password encryption
- Thinking sessions serve static files
- Mixing routing with session management
2. Which of the following is the correct way to initialize
express-session middleware in an Express app?easy
Solution
Step 1: Recall express-session syntax
The middleware is added withapp.use(session({ options })).Step 2: Check options correctness
Options likesecret,resave, andsaveUninitializedare standard.Final Answer:
app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true })) -> Option CQuick Check:
Use app.use(session({...})) with options [OK]
Hint: Use app.use(session({ secret, resave, saveUninitialized })) [OK]
Common Mistakes:
- Using app.session instead of app.use
- Passing secret as a string directly
- Calling non-existent methods like sessionMiddleware
3. Given this Express route using
express-session:
app.get('/dashboard', (req, res) => {
if (req.session.user) {
res.send(`Welcome, ${req.session.user}!`);
} else {
res.status(401).send('Please log in');
}
});
// Assume req.session.user = 'Alice'
What will the server respond when a logged-in user visits /dashboard?medium
Solution
Step 1: Check session user existence
The code checks ifreq.session.userexists; here it is 'Alice'.Step 2: Determine response
Since user exists, it sendsWelcome, Alice!as response.Final Answer:
Welcome, Alice! -> Option AQuick Check:
Session user present = welcome message [OK]
Hint: If req.session.user exists, show welcome message [OK]
Common Mistakes:
- Assuming undefined session user causes error
- Expecting redirect without code
- Confusing status 401 with success message
4. Consider this code snippet for session setup:
const session = require('express-session');
app.use(session({
secret: 'secret123',
resave: false
}));
What is the likely problem with this setup?medium
Solution
Step 1: Review required session options
Whilesecretandresaveare set,saveUninitializedis missing.Step 2: Understand saveUninitialized role
WithoutsaveUninitialized, some sessions may not be saved, causing unexpected behavior.Final Answer:
Missing saveUninitialized option may cause sessions not to save properly -> Option BQuick Check:
Always set saveUninitialized option [OK]
Hint: Always include saveUninitialized in session config [OK]
Common Mistakes:
- Thinking secret must be a number
- Believing resave must be true
- Adding middleware after routes
5. You want to protect a route so only logged-in users can access it using
express-session. Which middleware function correctly checks the session and redirects unauthorized users to /login?hard
Solution
Step 1: Understand middleware signature
Middleware must have(req, res, next)and callnext()to continue.Step 2: Check session user and redirect logic
Ifreq.session.userexists, callnext()to allow access; otherwise redirect to/login.Final Answer:
function auth(req, res, next) { if (req.session.user) next(); else res.redirect('/login'); } -> Option DQuick Check:
Session user? next() : redirect [OK]
Hint: Call next() if logged in; else redirect to login [OK]
Common Mistakes:
- Missing next() call in middleware
- Reversing condition logic
- Sending response instead of redirecting
