What are the differences between cookies, localStorage, and sessionStorage?

EasyPhone Screen
AmazonFrontend Engineer
234

Compare cookies, localStorage, and sessionStorage. What are the use cases, limitations, and security considerations for each?

1 Answer

189
Top Answer
FeatureCookieslocalStoragesessionStorage
Size~4KB~5MB~5MB
ExpirySet manuallyNeverTab close
Sent to serverYes, every requestNoNo
ScopeDomain + pathDomainTab only

When to Use:

Cookies:

  • Authentication tokens (HttpOnly, Secure flags)
  • Data needed by server
  • Cross-subdomain sharing

localStorage:

  • User preferences
  • Cached data
  • Shopping cart (non-sensitive)

sessionStorage:

  • Form data for multi-step forms
  • Temporary state within a tab
  • Data that shouldn't persist

Security Tips:

  • Never store sensitive data in localStorage (XSS vulnerable)
  • Use HttpOnly cookies for auth tokens
  • Set Secure flag for HTTPS-only cookies
  • Set SameSite attribute to prevent CSRF
StorageExpert

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Amazon

View all