Skip to content
beginnerPhase 29 · Web Foundations

Sessions

Learn session management, server-side sessions, and session-based authentication.

30m
0 problems
Topic Progress0%

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 });
  });
});

Session vs Cookies

Understanding when to use sessions vs cookies is essential for web development.

Comparison

Feature Cookies Sessions
Storage Client (browser) Server (database/Redis)
Size ~4KB Unlimited
Security Visible to client Hidden from client
Lifetime Configurable Server-controlled
Performance Sent with every request Only session ID sent
Scaling Easy (stateless) Hard (stateful)

When to Use Each

Use Cookies For:

  • Theme preferences
  • Language settings
  • Analytics tracking
  • Non-sensitive preferences

Use Sessions For:

  • User authentication
  • Shopping cart contents
  • Sensitive user data
  • Temporary state

Hybrid Approach

// Store session ID in cookie, data on server
app.use(session({
  cookie: { maxAge: 3600000 },  // 1 hour
  store: new RedisStore({ client: redisClient })
}));

// Store preferences in cookie (lightweight)
res.cookie('theme', 'dark', { maxAge: 2592000000 }); // 30 days

// Store auth in session (secure)
req.session.userId = user.id;

JWT vs Sessions

Feature Sessions JWT
Storage Server Client
Revocation Easy (delete from store) Hard (need blacklist)
State Server-side Stateless
Scaling Requires shared store Scales easily
// Session approach
req.session.userId = user.id;
// Server checks session store on each request

// JWT approach
const token = jwt.sign({ userId: user.id }, secret);
// Client sends token, server verifies without lookup

Practice Problems

0/3solved
Build Sessions Component

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 needed
Sessions Testing

Write 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 tests
Sessions Performance

Optimize 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 analysis

Quiz

1. Where is session data stored?

Question 1 options

2. Why should you regenerate session ID on login?

Question 2 options

3. What is the difference between absolute and idle timeout?

Question 3 options

4. When should you use cookies instead of sessions?

Question 4 options

Flashcards

Question

What is a session?

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?

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?

Answer

For high-performance, scalable session storage in production. Much faster than database storage.

Question

What is the difference between sessions and JWT?

Answer

Sessions store data on server (easy revocation). JWT stores data on client (stateless, harder to revoke).

Question

What is Sessions?

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:

  1. User logs in
  2. Server creates session with ID
  3. Session ID stored in cookie
  4. Server looks up session on each request
  5. 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