25. Local & Session Storage, Cookies
Why Storage & Cookies Matter
Modern web apps often need to remember user preferences, session info, or temporary state. Local storage, session storage, and cookies are key tools for persisting data on the client side.
Local Storage vs Session Storage
Both are part of the Web Storage API. The differences:
- Local Storage: persists data even after the browser is closed, until explicitly cleared.
- Session Storage: persists data only for the current tab session; closes when the tab is closed.
// Set items
localStorage.setItem('theme', 'dark');
sessionStorage.setItem('tempData', '123');
// Get items
console.log(localStorage.getItem('theme')); // 'dark'
console.log(sessionStorage.getItem('tempData')); // '123'
// Remove items
localStorage.removeItem('theme');
sessionStorage.clear();Using JSON in Storage
Web storage stores strings, so objects and arrays need to be serialized with `JSON.stringify()` and parsed with `JSON.parse()`.
const user = { name: 'Ada', age: 25 };
localStorage.setItem('user', JSON.stringify(user));
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.name); // 'Ada'Cookies Basics
Cookies are older than Web Storage and can be sent to the server with HTTP requests. They have expiration dates and can be used for authentication, tracking, and storing small data.
// Set a cookie
document.cookie = 'username=ada; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/';
// Read cookies
console.log(document.cookie); // 'username=ada'
// Delete cookie by setting past expiration
document.cookie = 'username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';Best Practices
- Avoid storing sensitive information in local storage or cookies without encryption.
- Use session storage for temporary, tab-specific data.
- Always validate and sanitize data retrieved from storage.
- Consider expiry and cleanup for stored data to prevent clutter.
Mini Challenge
1. Create a theme switcher that toggles between dark and light mode and remembers the choice using local storage. 2. Build a simple form that saves draft inputs in session storage, restoring them if the page is refreshed. 3. Set a cookie with the user's name and display a welcome message when the page loads.