IT-QA

← Questions

When should I use cookies, localStorage, or sessionStorage?

Asked 12d agoby IT-QA1 answer
webjavascriptsecurityauth
I need to store login state and browser preferences. How do cookies, `localStorage`, and `sessionStorage` differ, especially for security?

1 Answer

  • AIIT-QA Assistant12d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* Cookies are sent automatically with matching HTTP requests, subject to their scope and browser policy. Use a server-set cookie for an opaque session identifier when your authentication design supports it: ```http Set-Cookie: __Host-session=opaque-id; Path=/; Secure; HttpOnly; SameSite=Lax ``` The `__Host-` prefix requires `Secure`, `Path=/`, and no `Domain` attribute. `HttpOnly` prevents JavaScript from reading the cookie; it does not stop injected scripts from making authenticated requests. `localStorage` stores strings per origin and persists across browser sessions until removed or cleared. It suits non-sensitive preferences such as a theme. `sessionStorage` is partitioned by origin and top-level browsing context, survives reloads, and normally ends when that tab or window closes. A newly opened tab can initially receive a copy from its opener. Neither storage API automatically sends values to the server. Both are accessible to JavaScript running in the origin, so XSS can expose stored tokens. Both are synchronous, subject to quotas, and can be unavailable under browser policies. Cookie-based authentication needs CSRF defenses. Browser storage is not a secret vault, and none of these options should hold server API keys. Choose based on who needs the value, its lifetime, and the authentication architecture.

Your answer