๐๏ธ Web Storage: Your Browserโs Memory Box
The Story of Remembering Things
Imagine you have a magical locker at school. Every day when you come back, your stuff is still there! But waitโthereโs also a temporary pocket that empties when you leave.
Thatโs exactly how Web Storage works in your browser!
๐ Meet the Storage Family
Your browser has three ways to remember things:
graph TD A["Web Storage Family"] --> B["localStorage"] A --> C["sessionStorage"] A --> D["Cookies"] B --> E["Forever Locker ๐"] C --> F["Temporary Pocket ๐"] D --> G["Tiny Notes ๐"]
๐ฆ localStorage โ The Forever Locker
Think of it like: A locker that keeps your stuff FOREVER (until you clean it out).
What Makes It Special?
- โ Data stays even after closing the browser
- โ Holds about 5MB of data (like 5 million letters!)
- โ Same data across all tabs of the same website
How to Use It
Saving something:
// Save your favorite color
localStorage.setItem('color', 'blue');
// Save your name
localStorage.setItem('name', 'Alex');
Getting it back:
// Get your color back
let myColor = localStorage.getItem('color');
// myColor is now 'blue'
Removing something:
// Remove just one item
localStorage.removeItem('color');
// Clear EVERYTHING
localStorage.clear();
Real-Life Example ๐ฎ
When you set โDark Modeโ on a website and come back next weekโit remembers! Thatโs localStorage!
๐ฑ sessionStorage โ The Temporary Pocket
Think of it like: A pocket that empties when you leave the room.
What Makes It Different?
- โฐ Data disappears when you close the tab
- ๐ Each tab has its OWN pocket (they donโt share!)
- ๐ฆ Also holds about 5MB
How to Use It
Same commands as localStorage!
// Save something for this session
sessionStorage.setItem('cart', 'apple');
// Get it back
let item = sessionStorage.getItem('cart');
// Remove it
sessionStorage.removeItem('cart');
// Clear all
sessionStorage.clear();
When to Use It? ๐
- Shopping cart items while browsing
- Form data youโre filling out
- Temporary quiz scores
๐ ๏ธ Storage Methods โ Your Toolkit
Both localStorage and sessionStorage share the same tools:
| Method | What It Does | Example |
|---|---|---|
setItem(key, value) |
Save data | setItem('age', '10') |
getItem(key) |
Get data | getItem('age') โ '10' |
removeItem(key) |
Delete one item | removeItem('age') |
clear() |
Delete ALL items | clear() |
key(index) |
Get key by position | key(0) โ 'age' |
length |
Count items | storage.length โ 1 |
๐ก Important Secret!
Storage only saves strings! Want to save an object?
// Saving an object
let user = {name: 'Sam', age: 12};
localStorage.setItem('user',
JSON.stringify(user));
// Getting it back
let savedUser = JSON.parse(
localStorage.getItem('user')
);
๐ข Storage Event โ When Things Change
Think of it like: A doorbell that rings when someone changes your locker!
How It Works
When localStorage changes in another tab, your tab gets notified!
window.addEventListener('storage',
function(event) {
console.log('Something changed!');
console.log('Key:', event.key);
console.log('Old:', event.oldValue);
console.log('New:', event.newValue);
});
The Event Tells You:
keyโ Which item changedoldValueโ What it was beforenewValueโ What it is nowurlโ Which page made the changestorageAreaโ localStorage or sessionStorage
๐ฏ Cool Use Case
If you log out in one tab, ALL your tabs can know and log out too!
๐ช Cookies โ The Original Memory Notes
Think of it like: Tiny sticky notes that travel with you everywhere.
What Are Cookies?
- ๐ Very small (only 4KB each)
- ๐ Sent to the server with every request
- โฐ Can have expiration dates
- ๐ Can be protected
Creating a Cookie
// Simple cookie
document.cookie = "username=Alex";
// Cookie with expiration (7 days)
let date = new Date();
date.setTime(date.getTime() +
(7 * 24 * 60 * 60 * 1000));
document.cookie = "username=Alex;" +
"expires=" + date.toUTCString();
Reading Cookies
// Get all cookies (one big string)
let allCookies = document.cookie;
// "username=Alex; theme=dark"
Deleting a Cookie
// Set expiration to past date
document.cookie =
"username=; expires=Thu, 01 Jan 1970";
๐ท๏ธ Cookie Attributes โ The Rules
Cookies can have special instructions:
graph TD A["Cookie Attributes"] --> B["expires/max-age"] A --> C["path"] A --> D["domain"] A --> E["secure"] A --> F["HttpOnly"] A --> G["SameSite"]
expires / max-age
When should the cookie disappear?
// Expires on a specific date
document.cookie = "name=Alex;" +
"expires=Fri, 31 Dec 2025 23:59:59 GMT";
// Expires after 3600 seconds (1 hour)
document.cookie = "name=Alex;" +
"max-age=3600";
path
Which pages can see this cookie?
// Only pages under /shop/ can see it
document.cookie = "cart=3; path=/shop/";
// All pages can see it
document.cookie = "theme=dark; path=/";
domain
Which website addresses can access it?
// Only this exact site
document.cookie = "user=Sam;" +
"domain=example.com";
secure
Only send on HTTPS (safe connections)
document.cookie = "token=abc123;" +
"secure";
HttpOnly
JavaScript canโt touch this cookie! (Only set by the server, for safety)
SameSite
Stop cookie from being sent to other sites
// Strict: only your site
document.cookie = "id=123; SameSite=Strict";
// Lax: some exceptions allowed
document.cookie = "id=123; SameSite=Lax";
// None: sent everywhere (needs Secure)
document.cookie = "id=123;" +
"SameSite=None; Secure";
๐ Quick Comparison
| Feature | localStorage | sessionStorage | Cookies |
|---|---|---|---|
| Size | ~5MB | ~5MB | ~4KB |
| Expires | Never | Tab close | You decide |
| Sent to server | No | No | Yes! |
| Accessible from | All tabs | Current tab | All tabs |
๐ฏ When to Use What?
graph TD A["What do you need?"] --> B{Sent to server?} B -->|Yes| C["Use Cookies ๐ช"] B -->|No| D{Need it later?} D -->|Yes forever| E["localStorage ๐ฆ"] D -->|Just for now| F["sessionStorage ๐ฑ"]
Use localStorage for:
- ๐จ User preferences (theme, language)
- ๐ Game high scores
- ๐ Draft content
Use sessionStorage for:
- ๐ Shopping cart during browsing
- ๐ Form data being filled
- ๐ข One-time codes
Use Cookies for:
- ๐ Login sessions
- ๐ Analytics tracking
- ๐ฏ Personalization that needs server access
๐ You Did It!
Now you understand how browsers remember things:
- localStorage โ Forever memory, lots of space
- sessionStorage โ Temporary memory, per tab
- Storage methods โ setItem, getItem, removeItem, clear
- Storage events โ Know when things change
- Cookies โ Tiny notes that travel to the server
- Cookie attributes โ Control who, when, where
Youโre now a Web Storage Master! ๐
