Script Valley
Web Security Fundamentals for Developers
Authentication and Session SecurityLesson 4.3

Session fixation and session hijacking: how to secure session IDs

session fixation attack, session regeneration on login, session hijacking, secure and httpOnly cookie flags, session expiry, express-session configuration

Session Security

Session fixation attack diagram

Session security is about ensuring that a session ID cannot be predicted, stolen, or reused by an attacker.

Session Fixation

An attacker tricks a victim into using a session ID the attacker already knows. After the victim logs in, the attacker uses the same ID to access the authenticated session.

Fix: Always regenerate the session ID on login.

const session = require('express-session');

app.use(session({
  secret: process.env.SESSION_SECRET, // Strong, random secret
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true,   // Inaccessible to JavaScript
    secure: true,     // HTTPS only
    sameSite: 'Lax',  // CSRF protection
    maxAge: 30 * 60 * 1000 // 30 minutes
  }
}));

// On successful login — regenerate to prevent fixation
app.post('/login', (req, res) => {
  // ... validate credentials ...
  req.session.regenerate((err) => {
    if (err) return res.status(500).json({ error: 'Session error' });
    req.session.userId = user.id;
    res.json({ status: 'Logged in' });
  });
});

// On logout — destroy the session
app.post('/logout', (req, res) => {
  req.session.destroy(() => {
    res.clearCookie('connect.sid');
    res.json({ status: 'Logged out' });
  });
});

Session Expiry

Set absolute expiry (maxAge) so sessions don't persist indefinitely. For sensitive applications (banking, admin), also implement idle timeout by tracking req.session.lastActivity and invalidating sessions inactive for more than N minutes.

Up next

Rate limiting and account lockout to stop brute force attacks

Sign in to track progress

Session fixation and session hijacking: how to secure session IDs — Authentication and Session Security — Web Security Fundamentals for Developers — Script Valley — Script Valley