Frontend Patterns

Pattern

Secure Token Storage

Store authentication tokens safely using httpOnly cookies, secure flags, or encrypted storage to prevent token theft.

Secure Token Storage

Problem

Authentication tokens stored in localStorage or sessionStorage are accessible to any JavaScript code, including malicious scripts from XSS attacks. Stolen tokens allow attackers to impersonate users, access protected resources, and maintain persistent access even after the original session ends.

Solution

Store authentication tokens securely to prevent theft through XSS or other attacks. This protects user sessions and prevents unauthorized access.

Example

This demonstrates how to securely store authentication tokens using httpOnly cookies instead of localStorage, preventing XSS attacks from stealing user credentials.

// Store token in httpOnly cookie (server-side)
res.cookie('token', jwt, {
  httpOnly: true,      // Prevents JavaScript access, mitigating XSS attacks
  secure: true,        // Only send over HTTPS
  sameSite: 'strict',  // Prevent CSRF attacks
  maxAge: 3600000      // Token expires in 1 hour
});

// Not in localStorage
// localStorage.setItem('token', jwt); // Vulnerable to XSS - AVOID THIS

Benefits

  • Protects tokens from XSS attacks by using httpOnly cookies.
  • Prevents CSRF attacks when combined with SameSite attribute.
  • Reduces risk of token theft through secure storage mechanisms.
  • Protects user sessions and prevents unauthorized access.

Tradeoffs

  • httpOnly cookies can’t be accessed by JavaScript, complicating client-side logic.
  • Requires server-side configuration and coordination.
  • May complicate mobile app authentication flows.
  • Needs careful handling of token refresh and expiration.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.