localStorage vs sessionStorage vs Cookies

Three client-side storage mechanisms with different lifetimes, size limits, and use cases.

FeaturelocalStoragesessionStorageCookies
APIsetItem/getItem/removeItemsetItem/getItem/removeItemdocument.cookie (awkward)
Best forUser preferences, theme, cached dataForm data, temporary state per tabAuthentication tokens, server-readable state
LifetimePermanent (until manually cleared)Until tab/window closesConfigurable (expires/max-age)
Size limit~5-10 MB~5-10 MB~4 KB per cookie
Accessible fromSame originSame origin, same tabConfigurable (domain, path, SameSite)
Sent with requestsNoNoYes (every HTTP request)

Verdict

Use localStorage for persistent client-side data. Use sessionStorage for per-tab temporary data. Use cookies only for data the server needs to read (auth tokens). Never store sensitive data in any of these without encryption.

Code Example

Javascript
Tip: Modify the code above and click “Run” to see the results

Related Tutorials

Related Glossary Terms