Introduction
When building modern web applications, choosing the right browser storage solution is essential for ensuring performance, security, and a smooth user experience.
Developers often decide between localStorage, sessionStorage, and cookies—three popular forms of client-side storage used in today’s web development landscape.
Whether you’re comparing localStorage vs sessionStorage or wondering when to use cookies instead of localStorage, you’ll gain practical insights to make an informed choice tailored to your project’s specific needs.
Browser Storage Explained: localStorage vs. sessionStorage vs. Cookies - What You Need to Know
Feature | localStorage | sessionStorage | Cookies |
---|---|---|---|
Definition | Stores data with no expiration. Data persists even after browser is closed. | Stores data for one session. Data is cleared when the tab or window is closed. | Small pieces of data stored in the browser and sent with every HTTP request. Can have expiration or be session-based. |
Storage Capacity | High 5–10 MB | High 5 - 10 MB | Low 4KB |
Storage Quotas by Browser | localStorage is limited to approximately 5 MB per origin in most browsers. This can vary slightly depending on the browser and device. Chrome = approximately 10 MB Firefox = approximately 10 MB Safari = approximately 5 MB Edge = approximately 10 MB |
sessionStorage has the same storage limits as localStorage, since both use the Web Storage API. The approximate limits by browser are: Chrome = approximately 10 MB Firefox = approximately 10 MB Safari = approximately 5 MB Edge = approximately 10 MB |
Cookies are typically limited to ~4 KB per cookie, with most browsers allowing between 20 and 180 cookies per domain. The exact number varies by browser: Chrome = approximately 180 cookies per domain Firefox = approximately 150 cookies per domain Safari = approximately 50 cookies per domain |
Data Encryption / Format | Plain text strings; usually JSON serialized; no encryption. | Same as localStorage; plain text, no encryption. | Plain text name=value; no encryption unless manually added. |
Data Expiry | Never (manual deletion only) | On tab or window close | Can be set per cookie using either expires (specific date/time) or max-age (duration in seconds). If neither is set, cookie lasts only for the session and expires when browser/tab closes. |
Accessibility Scope | Accessible from all tabs and windows on the same website (origin: protocol, domain, and port) and persists even after closing and reopening the browser. | Only available in the specific tab or window where it was created, sessionStorage does not share data with other tabs - even within the same window. The data is deleted when that tab or window is closed. | Available to all tabs and windows on the same website, matching that domain and path. Cookies persist until they expire or are manually deleted. |
Data Access Scope | Client-side only (accessible via JavaScript) | Client-side only (accessible via JavaScript) | Client-side accessible via JavaScript unless marked HttpOnly; also sent to the server with each HTTP request |
Sent with HTTP Requests | No - Not sent automatically with HTTP requests. Must be manually included in requests via JavaScript (e.g., in headers or body). |
Same as localStorage No - Not sent automatically with HTTP requests. Must be manually included in requests via JavaScript (e.g., in headers or body). |
Yes - Sent with matching HTTP requests Automatically sent with every HTTP request to the website matching their domain and path. |
Persistent Across Sessions | Yes Data stays saved until you delete it. |
No Data is erased when you close the browser tab or window. |
Sometimes Data stays saved only if the cookie has an expiration date; otherwise, it’s deleted when the session ends. |
Security | Vulnerable to XSS attacks (where malicious scripts can access stored data via JavaScript) | Vulnerable to XSS attacks (malicious scripts can access session data within the tab) | Vulnerable to XSS (if not HttpOnly) and CSRF attacks (unauthorized commands sent from a user’s browser) unless properly secured with flags like HttpOnly and SameSite |
Security Best Practices |
|
Same security risks as localStorage (mainly vulnerable to XSS) |
|
Where We Can Use | Saving user theme preferences (dark/light mode), storing shopping cart items on e-commerce sites, caching app data for offline use (e.g., notes apps), saving game progress in browser games. | Preserving multi-step form data while filling a signup or checkout form, keeping temporary state like current page in a tab, storing session-specific flags during a single browsing session. | Maintaining login sessions, storing authentication tokens or session IDs, tracking user behavior across visits (analytics), saving language or region preferences, remembering cookie consent banners. |
Used by Major Brands (Examples) | Netflix: Saves user playback settings and preferences. Spotify: Stores offline playlists and user preferences. Amazon: Saves cart items locally for guest users. |
Google Docs: Keeps document state and unsaved changes within the tab. Facebook: Preserves temporary UI state during session. LinkedIn: Stores temporary navigation state. |
Facebook: Manages user sessions and personalization. Google: Uses cookies for login, preferences, and tracking. Twitter: Maintains authentication and user session data. |
Physical Storage Location | Not able to directly access files/folders on device. Stored in the browser’s Web Storage area on the user’s device, typically within browser-managed files (such as IndexedDB or SQLite). This data can be viewed using the browser’s developer tools (Application or Storage tab → Local Storage). |
Not able to directly access files/folders on device. Same storage location as localStorage, but data lasts only for the session. |
Not able to directly access files/folders on device. Stored as small text files managed by the browser, accessible via document.cookie or HTTP headers. Cookies can be viewed in browser developer tools under the Application or Storage tab → Cookies. |
Ease of Use | Easy Simple API (setItem(), getItem(), removeItem()); easy to implement and use for storing key-value pairs. |
Easy Same simple API as localStorage; limited to the session scope but equally easy to use. |
Hard More complex, string-based API (document.cookie); requires manual parsing, careful formatting, and security considerations, making implementation harder. |
Language Support | JavaScript in browsers only | JavaScript in browsers only | JavaScript on the client and any server-side language via HTTP headers. |
Learning Curve | Easy to learn and use | Easy to learn and use | Medium difficulty due to manual string parsing, managing attributes, and security considerations |
Storage API Methods / Commands | setItem(key, value): Stores data under the specified key getItem(key): Retrieves data for the given key removeItem(key): Deletes the key/value pair |
SessionStorage uses the same simple API as localStorage, including methods like setItem(), getItem(), and removeItem(). | Accessed via the document.cookie string Requires manual parsing to read individual cookies Setting cookies involves string manipulation (name=value pairs, expiration, path, etc.) |
Browser Compatibility | All Supported in all modern, older, and mobile browsers. |
All Supported in all modern, older, and mobile browsers |
All Supported in all modern, older, and mobile browsers - cookies have the broadest compatibility among browser storage options and work even in legacy environments (i.e., very old browsers or systems with limited modern web API support). |
Performance | Fast Read/write operations are quick with minimal impact on page load. Data is stored locally and not sent with network requests. |
Fast Same performance as localStorage. Efficient for short-term data during a session. |
Slower Slight performance overhead (extra effort/resources needed that can make things a bit slower) as cookies are sent with every HTTP request. Can impact performance if cookies are large or numerous. |
Regulatory Compliance | Must be handled carefully under GDPR/CCPA when storing personal data; users need to be informed, and consent must be obtained if data is personal or used for tracking. | Same as localStorage; session data is usually less sensitive but still subject to privacy regulations depending on the stored content. | Strictly regulated under GDPR/CCPA due to their tracking potential; require explicit user consent, clear cookie policies, and proper management to ensure compliance. |
Offline Support | Yes Data is available offline and commonly used in Progressive Web Apps (PWAs) for offline caching or storing app state. |
Yes Data remains accessible during the session even without an internet connection. |
Limited Cookies work offline but are mainly for sending data to the server when online (like keeping you logged in), so they’re not good for storing data to use offline. |
Behavior When Storage Quota Exceeds | Throws a QuotaExceededError if you try to store more data than the limit. No automatic cleanup - you need to handle errors manually. | Same as localStorage - throws QuotaExceededError when storage limit is exceeded. | Browsers may silently delete cookies (usually the oldest or largest) when quota is exceeded. No error is thrown in JavaScript. |
Summary
localStorage
- Stores data with no expiration.
- Data stays even after closing the browser.
- Capacity: 5–10 MB.
- Use for: Saving user preferences, cart items, offline data.
- Not sent with HTTP requests.
- Vulnerable to XSS, but easy to use with setItem() and getItem().
sessionStorage
- Stores data only for the current session.
- Cleared when the tab or window is closed.
- Capacity: 5–10 MB.
- Use for: Multi-step forms, tab-specific states.
- Not sent with HTTP requests.
- Lightweight and secure for short-term data.
Cookies
- Small data stored and sent with every HTTP request.
- Can expire or be session-based.
- Capacity: 4KB per cookie.
- Use for: Authentication, user sessions, tracking, preferences.
- Supports HttpOnly, Secure, and SameSite flags.
- Accessible via document.cookie; server-readable.
Frequently Asked Questions (FAQs)
-
Does localStorage or sessionStorage work in incognito or private browsing mode in JavaScript?
No, both localStorage and sessionStorage generally work in incognito or private mode, but:- The data is cleared automatically when the incognito session ends.
- Storage limits may be reduced in private mode.
- Some browsers may block or restrict it for privacy reasons.
-
What are the differences between localStorage, sessionStorage, and cookies?
localStorage retains data indefinitely until it is manually cleared, sessionStorage stores data only for the duration of the browser tab, and cookies have configurable expiration dates and are automatically sent with every HTTP request.
-
Is sessionStorage cleared when I reload or refresh the page?
No, sessionStorage is not cleared on page refresh.
It only gets cleared when the tab or browser window is closed. Refreshing the page keeps the data intact within the same session.
-
Is Web Storage supported on mobile browsers like Safari, Chrome, and Firefox?
Yes, Web Storage (localStorage and sessionStorage) is supported on major mobile browsers like Safari, Chrome, and Firefox.
It works reliably across most modern mobile devices and browsers.
However, on some older or privacy-restricted devices, storage may be limited or disabled in private mode. Always test on target devices.
-
Can localStorage be accessed by different subdomains?
No, localStorage is scoped to the origin, which includes:
Protocol (http/https)
Domain
Port (if applicable)
For example:
app.example.com and admin.example.com do not share localStorage.
You must use cookies with a shared domain setting if cross-subdomain access is required.
-
Can JavaScript disable cookies but still use localStorage?
Yes, When cookies are blocked, disabled, or not working, developers often use localStorage to save data on the user’s browser.
In this way, localStorage acts as a reliable fallback option to store information when cookies aren’t available.
-
Can localStorage be cleared automatically or expire?
No, localStorage does not expire or clear automatically
Data remains stored until you explicitly delete it using code (e.g., `localStorage.removeItem()`) or the user clears it manually through browser settings.
If you need data to expire, you must implement this yourself by saving a timestamp and checking it whenever you retrieve the data.
-
Is it secure to store sensitive information in localStorage or cookies?
No. Both localStorage and cookies are accessible via JavaScript and are vulnerable to XSS attacks. Sensitive data should be stored securely on the server or protected using encrypted, HttpOnly cookies that are inaccessible to JavaScript.
-
Can I set an expiry time for localStorage data manually in JavaScript?
Yes. SincelocalStorage
does not expire on its own, you can simulate expiration by storing a timestamp alongside your data and checking it when retrieving the data.
-
What happens when localStorage or sessionStorage quota is exceeded?
The browser throws a QuotaExceededError, and no further data can be written until space is freed. The limit is typically around 5–10 MB.
-
How do cookies affect website performance compared to localStorage?
Cookies are sent with every HTTP request, which can slow down performance, especially with large data. localStorage is not sent with requests, making it more efficient for storing non-critical client-side data.
-
How to clear localStorage, sessionStorage, and cookies programmatically?
Use localStorage.clear(), sessionStorage.clear(), and document.cookie manipulation for cookies.
-
How to securely store user authentication tokens using localStorage or cookies?
Prefer HttpOnly, Secure cookies for sensitive tokens; avoid localStorage due to XSS risks.
-
Can localStorage be accessed by third-party scripts?
Yes, any script running on the page’s origin can access localStorage, which raises security concerns.
-
Is it better to use cookies or localStorage for session management?
Cookies are better for sessions due to HTTP-only flag and automatic transmission; localStorage is less secure.