LocalStorage vs. Cookies: A Guide to Browser Storage

When building web applications, developers often need to store data in the browser to maintain state or communicate with the server. While there are three main types of browser storage—Session Storage, LocalStorage, and Cookies—this post focuses on the two most common permanent storage methods: LocalStorage and Cookies.
Here is a breakdown of how they compare in terms of lifespan, capacity, security, and use cases.
1. Lifespan
LocalStorage: Data here never expires. It persists until the user manually clears their browser cache or local data.
Cookies: The lifespan is configurable. Developers can set a specific expiry time/date when creating the cookie.
2. Capacity
LocalStorage: Offers a larger capacity, allowing you to store up to 10MB of data.
Cookies: Very limited storage. You can only store a small amount of data, typically around 4KB.
3. How It Is Set
LocalStorage: Data is set explicitly on the client-side using JavaScript.
Cookies: Data is usually set by the server. A key feature of cookies is that they are automatically sent to the server with every HTTP request.
4. Security
Security is the most critical difference between the two.
LocalStorage
LocalStorage is vulnerable to XSS (Cross-Site Scripting).
The Risk: If an attacker can run a script on your page, they can easily access tokens stored here (e.g., localStorage.getItem("Token")). They can then use this token to impersonate the user, as the backend will verify it as a valid token.
Cookies
Cookies are generally more secure against XSS, provided they are configured correctly.
The Benefit: If you use the HttpOnly flag, client-side scripts cannot access the cookie data.
The Risk: Cookies are vulnerable to CSRF (Cross-Site Request Forgery). The Solution: You can prevent CSRF by utilizing specific configuration flags:
HttpOnly (Prevents access via JavaScript)
Secure (Ensures transmission only over HTTPS)
SameSite (Controls when cookies are sent with cross-site requests)
5. Use Cases
LocalStorage: Best used for non-sensitive data persistence.
Example: Saving a user's shopping cart. If the user leaves and comes back, the cart data is still available without needing a server call.
Cookies: Best used for Authorization.
Example: Checking if a user is logged in. Since the cookie is sent automatically with every request, the server can validate the user instantly. With LocalStorage, you must manually attach a "Bearer Token" to the headers of every request.
Conclusion
Dealing with cookies can be more difficult than LocalStorage because you have to manage strict configuration flags like HttpOnly, Secure, and SameSite. However, for authentication and sensitive data, Cookies are the more secure choice. For simple, non-sensitive UI state (like a shopping cart or dark mode preference), LocalStorage is the better option.