TechnicalEasy HTTP & REST APIs

What is the difference between cookies, localStorage and sessionStorage?

Asked for Frontend Developer, Full-Stack Developer

Why they ask this: Choosing where to store tokens and preferences affects both security and user experience.

Answer

CookieslocalStoragesessionStorage
Sizeabout 4 KB eachabout 5 MBabout 5 MB
Sent to the server automaticallyyes, with every matching requestnono
Lifetimeuntil Expires/Max-Age, or the sessionuntil cleareduntil the tab closes
Readable by JavaScriptunless HttpOnlyyesyes

Security notes:

  • Store auth tokens in HttpOnly, Secure, SameSite cookies where possible, so an XSS attack cannot read them.
  • Anything in localStorage can be stolen by any script running on the page.
  • Use localStorage for non-sensitive preferences such as the theme or a saved filter.

Can you explain this in your own words?

Back to question bank