Local Storage vs Cookies vs IndexedDB: Where Should You Store Data?
Gone are the days when specific user settings required server-side databases. Today's browsers are powerful storage engines. Here is how to pick the right one.
Modern web applications, especially Single Page Applications (SPAs), rely heavily on client-side storage. Whether it's caching API responses, saving a dark mode preference, or keeping a user logged in, you have three main choices: LocalStorage, Cookies, and IndexedDB.
Each has a specific purpose, and misuse can lead to security vulnerabilities or performance bottlenecks.
1. Cookies: The Old Guard
Cookies are the oldest form of client storage. They are small (4KB max) text files sent with every single HTTP request to your domain.
Use Case: Authentication.
Because cookies are sent automatically to the server, they are perfect for session tokens (JWTs). By marking a cookie as `HttpOnly`, you prevent JavaScript from accessing it, making your app immune to Cross-Site Scripting (XSS) attacks that try to steal tokens.
Don't use for: Storing large amounts of data. It slows down every request.
2. LocalStorage: Simple & Synchronous
LocalStorage is a key-value store that persists until the user clears their browser cache. It's easy to use (`localStorage.setItem('key', 'value')`) and offers about 5MB of space.
Use Case: User Preferences.
Perfect for things like theme settings (Light/Dark mode), sidebar collapsed state, or temporary form data (so users don't lose work if they refresh).
Warning: LocalStorage is synchronous. If you try to read a massive JSON object from it, you will freeze the main thread and the UI will stutter.
3. IndexedDB: The Heavy Lifter
IndexedDB is a full-blown transactional database running inside the browser. It's asynchronous (won't block the UI), supports indexes for fast searching, and can store huge amounts of structured data (hundreds of MBs).
Use Case: Offline Apps & Complex Data.
If you're building a PWA (Progressive Web App) that works offline, IndexedDB is where you cache your API responses, images, and user-generated content.
Summary Table
| Storage | Capacity | Performance | Best For |
|---|---|---|---|
| Cookies | 4KB | Slow (Network) | Auth Tokens |
| LocalStorage | 5MB | Blocking (Sync) | Simple Configs |
| IndexedDB | >500MB | Fast (Async) | Complex Data |
At ToolBit, we use LocalStorage to remember your preferences (like staying in "Hex" mode on the color picker) because it's fast, simple, and privacy-friendly. No data ever leaves your device.