Local Storage, Session Storage, and Cookies
Why Client-Side Storage?
Web applications often need to remember information between page visits: a user's preferences, a shopping cart, login state, or partially completed forms. Client-side storage lets the browser hold this data without always sending it to a server.
localStorage
localStorage stores data with no expiry — data persists until explicitly removed, even after the browser is closed.
// Store a value (strings only — values must be strings)
localStorage.setItem("theme", "dark");
localStorage.setItem("language", "en");
// Retrieve a value
const theme = localStorage.getItem("theme");
console.log(theme); // "dark"
// Remove a specific item
localStorage.removeItem("language");
// Clear all localStorage items for this domain
localStorage.clear();
// Check if an item exists
const saved = localStorage.getItem("nonexistent");
console.log(saved); // null — not "undefined"
Storing Objects and Arrays
localStorage only stores strings. Use JSON.stringify and JSON.parse to store complex data:
const userPrefs = {
theme: "dark",
fontSize: 16,
notifications: true
};
// Save object
localStorage.setItem("preferences", JSON.stringify(userPrefs));
// Load object
const saved = localStorage.getItem("preferences");
const prefs = saved ? JSON.parse(saved) : {};
console.log(prefs.theme); // "dark"
A helpful pattern — save and load with defaults:
function savePrefs(prefs) {
localStorage.setItem("app_prefs", JSON.stringify(prefs));
}
function loadPrefs() {
const raw = localStorage.getItem("app_prefs");
return raw ? JSON.parse(raw) : { theme: "light", lang: "en" };
}
sessionStorage
sessionStorage works identically to localStorage but data is cleared when the browser tab is closed:
sessionStorage.setItem("currentStep", "3");
const step = sessionStorage.getItem("currentStep");
console.log(step); // "3"
sessionStorage.removeItem("currentStep");
Use sessionStorage for temporary data within a single session — like a multi-step form's current progress or a temporary filter state.
Cookies
Cookies are the oldest client-side storage mechanism. They differ from localStorage in key ways:
- They can be sent to the server with every HTTP request
- They have an expiry date
- They can be restricted to specific paths and domains
- They have a smaller size limit (around 4KB vs 5MB for localStorage)
// Set a cookie (expires in 7 days)
const expires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toUTCString();
document.cookie = `username=Amara; expires=${expires}; path=/`;
// Read cookies (returns all cookies as a single string)
console.log(document.cookie); // "username=Amara; theme=dark"
// Parse a specific cookie
function getCookie(name) {
const cookies = document.cookie.split("; ");
const found = cookies.find(c => c.startsWith(name + "="));
return found ? found.split("=")[1] : null;
}
console.log(getCookie("username")); // "Amara"
In practice, most modern applications manage cookies through the server (using Set-Cookie HTTP headers) or through a library, rather than using document.cookie directly.
When to Use Each
| localStorage | sessionStorage | Cookies | |
|---|---|---|---|
| Persists after tab close | Yes | No | Configurable |
| Persists after browser close | Yes | No | Configurable |
| Sent to server | No | No | Yes |
| Size limit | ~5MB | ~5MB | ~4KB |
| Best for | User preferences, cached data | Current session state | Auth tokens (server-managed) |
Security Considerations
- Never store sensitive data (passwords, credit card numbers) in localStorage or sessionStorage — they are accessible to any JavaScript running on the page, including scripts from third-party libraries
- Use
HttpOnlycookies (set by the server) for authentication tokens — they cannot be read by JavaScript, which protects against Cross-Site Scripting (XSS) attacks - localStorage is not available in private/incognito mode in some browsers, so always handle
localStorageinside a try/catch or check for its availability
Key Takeaways
- localStorage persists indefinitely; sessionStorage clears when the tab is closed; cookies have a configurable expiry
- All three storage mechanisms are domain-specific — data from one site cannot be read by another
- Always use JSON.stringify() to store objects and JSON.parse() to retrieve them from localStorage
- Cookies are sent with every HTTP request, making them suitable for server-managed authentication
- Never store passwords, tokens, or sensitive data in localStorage — use HttpOnly cookies set by the server for that
- Wrap localStorage access in try/catch to handle private browsing mode where it may be unavailable
Practice Exercise
- Build a theme toggle (light/dark) that saves the user's choice to
localStorageand applies it on page load - Add a form that saves its field values to
sessionStorageon every keystroke, so data is not lost on accidental refresh - Write a
storageHelperobject withget(key, defaultValue),set(key, value), andremove(key)methods that handle JSON serialisation internally
Try it yourself
Key Takeaways
- localStorage stores data indefinitely (until cleared); sessionStorage clears when the browser tab is closed
- Both localStorage and sessionStorage store strings only — use JSON.stringify and JSON.parse for objects
- Cookies can be sent to the server with every HTTP request and have a configurable expiry date
- localStorage and sessionStorage have a ~5MB limit per domain; cookies are limited to ~4KB
- Never store passwords or sensitive tokens in localStorage — use HttpOnly server-set cookies for authentication
- Always wrap localStorage access in try/catch to handle private browsing environments where it may be disabled
Quick Quiz
1.What is the main difference between localStorage and sessionStorage?
2.Why do you need JSON.stringify() to store an object in localStorage?
3.Why should sensitive data like passwords never be stored in localStorage?
4.Which storage option sends data to the server with every HTTP request?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx