Advertisement
Advanced JavaScript, Browser Storage & Web APIs

How do cookies differ from localStorage for storing data?

Short answer

Cookies are automatically sent with every HTTP request to their domain (adding overhead), have a much smaller size limit (~4KB), and can be marked HttpOnly so JavaScript can't read them at all — useful for session tokens.

Save JavaScript mock interview
Advertisement
AModel answer
Cookies are automatically sent with every HTTP request to their domain (adding overhead), have a much smaller size limit (~4KB), and can be marked HttpOnly so JavaScript can't read them at all — useful for session tokens. localStorage never travels with requests and is always JS-accessible.
document.cookie = 'sessionId=abc123; Secure; SameSite=Strict';
localStorage.setItem('sessionId', 'abc123'); // different use case
Real-world example
Storing an auth session token in an HttpOnly cookie to protect it from XSS, versus storing UI preferences in localStorage.
Likely follow-ups
  • What does the SameSite cookie attribute protect against?
Related topics