
Web Storage API provides two ways to store data on the client side:
- Local Storage: Stores data with no expiration date.
- Session Storage: Stores data for the duration of the page session.
💡 Key Difference
Local Storage persists data even after the browser is closed. Session Storage data is cleared when the tab or window is closed.
| Feature | Local Storage | Session Storage |
|---|---|---|
| Lifetime | Persistent, no expiration | Until tab/window closes |
| Scope | Shared across all tabs/windows from the same origin | Unique per tab/window |
| Storage limit | Typically 5-10 MB | Typically 5-10 MB |
| Access | window.localStorage | window.sessionStorage |
Basic API Methods
setItem(key, value): Stores a key-value pair.getItem(key): Retrieves the value by key.removeItem(key): Deletes the key and its value.clear(): Clears all stored data.key(index): Returns the key at the given index.length: Property indicating number of stored items.
⚠️ Important!
Both storage types only store strings. To store objects or arrays, convert them to JSON strings using JSON.stringify() and parse with JSON.parse() when retrieving.
📌 Deep Dive: Storing and Retrieving an Object in Local Storage
const user = { name: "Alice", age: 30 };
// Save object as string
localStorage.setItem("user", JSON.stringify(user));
// Retrieve and parse back to object
const storedUser = JSON.parse(localStorage.getItem("user"));
console.log(storedUser.name); // Alice
Use Cases
- Local Storage: Saving user preferences, themes, or tokens that persist across sessions.
- Session Storage: Storing temporary data like form inputs or session-specific info that shouldn't persist after closing the tab.
💡 Security Consideration
Never store sensitive data like passwords or personal info in web storage, as it is accessible by any script from the origin.
Example: Using Session Storage
- Store user input temporarily:
📌 Deep Dive: Session Storage Example
// Store data for this session
sessionStorage.setItem("visitedPage", "home");
// Retrieve data
console.log(sessionStorage.getItem("visitedPage")); // home
// Data removed when tab closes
⚠️ Browser Support
Modern browsers support web storage, but always check compatibility if targeting older browsers.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which storage type keeps data even after closing the browser?
Question 2 of 2
What must you do before storing an object in Local Storage?
Loading results...