Featured
- Get link
- X
- Other Apps
๐พ Day 20 — LocalStorage & SessionStorage
๐พ Day 20 — LocalStorage & SessionStorage
Hey guys Today we’ll learn how to store data inside the browser: what to store, how to store, and when to use LocalStorage vs SessionStorage — plus patterns for building resilient client-side storage.
๐ What are LocalStorage & SessionStorage?
The Web Storage API provides two simple key/value stores: localStorage and sessionStorage. They are synchronous, string-only, and scoped to the origin (protocol + host + port). Use them to persist small pieces of data on the client without a server.
๐ Differences at a glance
- localStorage — persists across browser sessions and survives closing the tab/window. Good for long-term preferences, offline drafts, and small caches.
- sessionStorage — lasts only for the tab session. When the tab is closed, data is cleared. Useful for one-tab temporary state like a multi-step form in a single session.
⚙️ Getting started — Basic API
// set
localStorage.setItem('theme', 'dark');
sessionStorage.setItem('formStep', '2');
// get
const theme = localStorage.getItem('theme');
// remove
localStorage.removeItem('theme');
// clear
sessionStorage.clear();
๐งญ Storing objects (serialize/deserialize)
The storage APIs save strings only. To store objects or arrays, convert them to JSON with JSON.stringify and back with JSON.parse.
const user = { id: 1, name: "Rahul", prefs: { theme: "dark" } };
localStorage.setItem('user', JSON.stringify(user));
const stored = JSON.parse(localStorage.getItem('user') || '{}');
console.log(stored.name); // "Rahul"
๐ Security & size considerations
- Never store secrets: Do NOT store passwords, tokens, or PII in plain localStorage. It’s accessible by any script running on the page (XSS risk).
- Size limits: Browsers typically allow ~5–10MB per origin. Use it for lightweight caching, not full data dumps.
- Quotes & escaping: JSON.stringify handles escaping—avoid manual string building.
๐ Common use cases
- Persist theme or UI preferences (dark/light, font-size).
- Cache API responses for quick UI rendering (with stale-while-revalidate).
- Save form drafts locally so users don’t lose work.
- Store feature flags or simple analytics markers.
๐งฉ Pattern: Namespaces & versioning
To avoid key collisions and make migration easier, use a namespace and include a version number:
const NS = "myapp:v1:";
function save(key, value) {
localStorage.setItem(NS + key, JSON.stringify(value));
}
function load(key) {
const raw = localStorage.getItem(NS + key);
return raw ? JSON.parse(raw) : null;
}
๐งฐ Pattern: Storage wrapper with fallback
Build a small wrapper to handle unavailable storage (private mode) and to provide graceful fallback to in-memory storage.
function storageAvailable(type = 'localStorage') {
try {
const storage = window[type];
const x = '__test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
} catch (e) {
return false;
}
}
const store = storageAvailable() ? localStorage : (function(){ let mem = {}; return { getItem:k=>mem[k]||null, setItem:(k,v)=>mem[k]=v, removeItem:k=>delete mem[k] } })();
๐ Practical example — Simple preferences
Save a theme preference and apply it on load.
// save
document.querySelector('#themeToggle').addEventListener('click', () => {
const current = localStorage.getItem('theme') === 'dark' ? 'light' : 'dark';
localStorage.setItem('theme', current);
document.documentElement.setAttribute('data-theme', current);
});
// apply on load
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
๐งช Mini tasks (practice)
- Save user form progress in localStorage and restore it on reload.
- Implement a stale-while-revalidate cache for a list endpoint: show cached data immediately, then refresh in background.
- Build a toggle for compact/comfortable layout and persist the choice.
๐งพ When NOT to use localStorage
- Don’t use it as a database for large datasets.
- Don’t store authentication tokens unless you understand XSS risks—prefer httpOnly cookies or IndexedDB with proper controls.
- Don’t use it for cross-origin data sharing; it’s origin-scoped.
✅ Summary
LocalStorage and SessionStorage are simple and useful for many client-side needs. Use JSON for objects, wrap the API for resilience, namespace keys, and avoid storing secrets. When you outgrow localStorage, consider IndexedDB or server-side persisting.
Popular Posts
๐ Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
๐จ Day 2: Headings, Paragraphs & Text Formatting
- Get link
- X
- Other Apps
Comments
Post a Comment