Gyaan

Web Storage & Cookies

beginner storage localStorage sessionStorage cookies browser

Browsers give us a few ways to store data on the client side. The three main ones are localStorage, sessionStorage, and cookies. They each have different lifetimes, sizes, and behaviors — let’s break them down.

localStorage
Persistence:
Forever (until cleared)
Size limit:
~5 MB
Sent to server:
No
Scope:
Same origin
sessionStorage
Persistence:
Until tab closes
Size limit:
~5 MB
Sent to server:
No
Scope:
Same origin + tab
Cookies
Persistence:
Until expiry date
Size limit:
~4 KB
Sent to server:
Yes, every request
Scope:
Same origin (configurable)

localStorage

Data stays even after we close the browser. It’s the most common one for things like user preferences, theme settings, or cached data.

// Store data (must be strings)
localStorage.setItem('theme', 'dark');
localStorage.setItem('user', JSON.stringify({ name: 'Manish' }));

// Read data
const theme = localStorage.getItem('theme'); // 'dark'
const user = JSON.parse(localStorage.getItem('user'));

// Remove one item
localStorage.removeItem('theme');

// Clear everything
localStorage.clear();

sessionStorage

Works exactly like localStorage, but the data is cleared when the tab is closed. If we open a new tab, it gets its own separate sessionStorage.

// Same API as localStorage
sessionStorage.setItem('formStep', '2');
const step = sessionStorage.getItem('formStep'); // '2'

// Gone when the tab is closed
sessionStorage.removeItem('formStep');

This is useful for temporary things like multi-step form data or a one-time banner that shouldn’t show again in the same session.

Cookies

Cookies are the oldest storage mechanism. The big difference is that cookies are sent to the server with every HTTP request — that’s why they’re used for authentication tokens. But the size limit is tiny (about 4KB).

// Set a cookie (expires in 7 days)
document.cookie = "username=Manish; expires=" +
  new Date(Date.now() + 7 * 86400000).toUTCString() + "; path=/";

// Read all cookies (returns one big string)
console.log(document.cookie); // "username=Manish; theme=dark"

// Delete a cookie (set expiry in the past)
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

The cookie API is honestly terrible to work with. That’s why most people use a small library or write helper functions.

When to Use Which

  • localStorage — User preferences, theme, cached API data, anything that should survive a browser restart
  • sessionStorage — Temporary form data, one-time notifications, wizard/step state within a single tab
  • Cookies — Authentication tokens, session IDs, anything the server needs to see on every request

In simple language, if the server doesn’t need it, use localStorage or sessionStorage. If the server needs to read it on every request (like an auth token), use cookies.