What is localstorage?
LocalStorage is a feature built into web browsers that lets a website store small pieces of data (like text or numbers) on your computer. The data stays there even after you close the browser or turn off your computer, and it can be read again the next time you visit the same site.
Let's break it down
- Key‑value pairs: Think of it like a simple spreadsheet where each row has a “key” (the name) and a “value” (the data).
- String only: Everything is saved as text, so numbers or objects need to be turned into strings first.
- Capacity: Usually about 5‑10 MB per domain, which is enough for settings, preferences, or a short list of items.
- API: You use four main commands -
setItem(key, value)
,getItem(key)
,removeItem(key)
, andclear()
- to write, read, delete, or wipe all data.
Why does it matter?
LocalStorage makes web apps feel faster and more personal. Because the data is saved locally, the site doesn’t have to ask a server for things like your theme choice or a shopping cart every time you load a page. This reduces network traffic, speeds up load times, and lets the app work offline for basic features.
Where is it used?
- Remembering user preferences (dark mode, language).
- Storing a temporary shopping cart before checkout.
- Caching small API responses to avoid repeated network calls.
- Saving game scores or progress in browser games.
- Keeping form data when a page reloads unexpectedly.
Good things about it
- Simple to use: Only a few lines of JavaScript are needed.
- Persistent: Data survives browser restarts and page reloads.
- Fast: Reading/writing is instant because it’s on the user’s device.
- No server required: Works completely client‑side, reducing backend load.
- Widely supported: All modern browsers (desktop and mobile) have it.
Not-so-good things
- Only strings: You must convert objects to JSON and back, which adds extra steps.
- Limited size: Large amounts of data (beyond ~5 MB) can’t be stored.
- No expiration: Data stays forever unless you manually delete it, which can lead to stale information.
- Security risks: Data is accessible to any script on the same domain, so XSS attacks can expose it.
- Not for sensitive info: Never store passwords, credit‑card numbers, or personal identifiers; it’s not encrypted.