Server-Side Sessions
Sessions store user state on the server, identified by a session ID stored in a cookie.
How Sessions Work
1. User logs in
POST /login {username: "alice", password: "secret"}
2. Server creates session
Session ID: abc123def456
Store: {userId: 1, role: "admin", loginTime: "2024-01-15"}
3. Server sends session cookie
Set-Cookie: session=abc123def456; HttpOnly; Secure; SameSite=Strict
4. Subsequent requests
GET /dashboard
Cookie: session=abc123def456
5. Server looks up session
Find session abc123def456 → {userId: 1, role: "admin"}
Use user data for request
Session Storage Options
| Storage | Use Case | Persistence |
|---|---|---|
| Memory | Development only | Lost on restart |
| Database | Production | Persistent |
| Redis | High-performance | Persistent |
| Memcached | Distributed | Volatile |
Express.js Session Example
const session = require('express-session');
const RedisStore = require('connect-redis').default;
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: true, // HTTPS only
httpOnly: true, // No JS access
maxAge: 3600000, // 1 hour
sameSite: 'strict'
}
}));
// Login route
app.post('/login', async (req, res) => {
const user = await authenticateUser(req.body);
if (user) {
req.session.userId = user.id;
req.session.role = user.role;
res.json({ success: true });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
// Protected route
app.get('/dashboard', (req, res) => {
if (!req.session.userId) {
return res.status(401).json({ error: 'Not authenticated' });
}
res.json({ userId: req.session.userId });
});
Session Management
Proper session management is critical for security and user experience.
Session Lifecycle
Creation → Active → Idle → Expiry → Destruction
1. Creation: User logs in, session created
2. Active: User makes requests, session valid
3. Idle: No activity, timeout countdown
4. Expiry: Session expires, user must re-login
5. Destruction: User logs out, session destroyed
Session Timeout Strategies
// Absolute timeout (fixed duration from creation)
const ABSOLUTE_TIMEOUT = 24 * 60 * 60 * 1000; // 24 hours
// Idle timeout (inactivity based)
const IDLE_TIMEOUT = 30 * 60 * 1000; // 30 minutes
// Check session validity
app.use((req, res, next) => {
if (req.session) {
const now = Date.now();
// Check absolute timeout
if (now - req.session.createdAt > ABSOLUTE_TIMEOUT) {
req.session.destroy();
return res.status(401).json({ error: 'Session expired' });
}
// Check idle timeout
if (now - req.session.lastActivity > IDLE_TIMEOUT) {
req.session.destroy();
return res.status(401).json({ error: 'Session expired' });
}
// Update last activity
req.session.lastActivity = now;
}
next();
});
Session Security
| Threat | Protection |
|---|---|
| Session Fixation | Regenerate ID on login |
| Session Hijacking | Secure, HttpOnly, SameSite flags |
| CSRF | SameSite attribute, CSRF tokens |
| Brute Force | Rate limiting, account lockout |
// Regenerate session ID on login (prevent fixation)
app.post('/login', async (req, res) => {
const user = await authenticateUser(req.body);
if (user) {
req.session.regenerate((err) => {
req.session.userId = user.id;
res.json({ success: true });
});
}
});
// Destroy session on logout
app.post('/logout', (req, res) => {
req.session.destroy((err) => {
res.clearCookie('session');
res.json({ success: true });
});
});
Practice Problems
Create a reusable React component implementing Sessions. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Sessions using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Sessions for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. Where is session data stored?
2. Why should you regenerate session ID on login?
3. What is the difference between absolute and idle timeout?
4. When should you use cookies instead of sessions?
Flashcards
Question
What is a session?
Click to reveal answer
Answer
Server-side storage for user state, identified by a session ID stored in a cookie. Used for authentication and sensitive data.
Question
What is session fixation?
Click to reveal answer
Answer
An attack where an attacker sets a known session ID before the user logs in. Prevented by regenerating session ID on login.
Question
When should you use Redis for sessions?
Click to reveal answer
Answer
For high-performance, scalable session storage in production. Much faster than database storage.
Question
What is the difference between sessions and JWT?
Click to reveal answer
Answer
Sessions store data on server (easy revocation). JWT stores data on client (stateless, harder to revoke).
Question
What is Sessions?
Click to reveal answer
Answer
Sessions is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.Sessions store data on the server, identified by a cookie
- 2.Regenerate session ID on login to prevent fixation attacks
- 3.Use Redis for high-performance session storage in production
- 4.Implement both absolute and idle timeouts
- 5.Use sessions for sensitive data, cookies for preferences
Interview Tips
- •Explain how sessions work from login to logout
- •Know how to prevent session fixation and hijacking
- •Understand when to use sessions vs cookies vs JWT
- •Be familiar with session timeout strategies
Cheat Sheet
Sessions Cheat Sheet
How Sessions Work:
- User logs in
- Server creates session with ID
- Session ID stored in cookie
- Server looks up session on each request
- Session data used for request
Session Security:
- Regenerate ID on login
- Use Secure, HttpOnly, SameSite flags
- Implement absolute and idle timeouts
- Rate limit login attempts
Session vs Cookies:
- Cookies: Client-side, ~4KB, visible to client
- Sessions: Server-side, unlimited, hidden
Storage Options:
- Memory: Development only
- Database: Production
- Redis: High-performance production
Timeouts:
- Absolute: Fixed duration from creation
- Idle: Resets on activity