Web Storage

Back

Loading concept...

๐Ÿ—„๏ธ 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 changed
  • oldValue โ€” What it was before
  • newValue โ€” What it is now
  • url โ€” Which page made the change
  • storageArea โ€” 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:

  1. localStorage โ€” Forever memory, lots of space
  2. sessionStorage โ€” Temporary memory, per tab
  3. Storage methods โ€” setItem, getItem, removeItem, clear
  4. Storage events โ€” Know when things change
  5. Cookies โ€” Tiny notes that travel to the server
  6. Cookie attributes โ€” Control who, when, where

Youโ€™re now a Web Storage Master! ๐ŸŽ‰

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.