← Back to Chapters

JavaScript Storage: localStorage & sessionStorage

? JavaScript Storage: localStorage & sessionStorage

? Quick Overview

Web Storage allows websites to store data directly in the user’s browser in the form of key–value pairs. It is more secure and provides more space than cookies, and it is not sent to the server on every request.

  • localStorage – data is stored without expiry (until cleared manually).
  • sessionStorage – data is stored for the current tab/session only.

Both are part of the Web Storage API and are available through the window object in modern browsers.

? Key Concepts

  • Data is stored as string key–value pairs.
  • Storage limit is usually around 5–10 MB per domain, which is much larger than cookies.
  • APIs are synchronous, so heavy usage can block the main thread.
  • Values persist on the client side only and are not automatically shared with the server.
  • Best suited for preferences, small caches, and temporary session data.

? Syntax & Theory

? localStorage (persistent)

  • localStorage.setItem(key, value) – store a value.
  • localStorage.getItem(key) – read a value.
  • localStorage.removeItem(key) – remove a single key.
  • localStorage.clear() – clear everything for that origin.

Data survives page reloads and browser restarts until the user clears it (or your script does).

? sessionStorage (per tab)

  • Same API as localStorage, but data exists only for the current tab.
  • Closing the tab or browser window will clear the stored data.
  • Opening the same page in a new tab creates a new sessionStorage.

Great for data that should not leak between tabs, such as temporary tokens or form steps.

? Use Cases & When to Use

  • Store UI preferences like theme, language, and layout using localStorage.
  • Keep temporary data such as wizard steps or short-lived tokens in sessionStorage.
  • Cache small API responses on the client to reduce network calls.
  • Remember “dismissed” states for banners or popups between visits.

? Code Examples

? Example: Using localStorage

Basic operations with localStorage to store and retrieve a username.

? View Code Example
// Set item
localStorage.setItem('username', 'Ashish');
// Get item
let user = localStorage.getItem('username');
console.log(user); // "Ashish"
// Remove item
localStorage.removeItem('username');
// Clear all items
localStorage.clear();

? Example: Using sessionStorage

Same API, but values exist only for the life of the browser tab/session.

? View Code Example
// Set item
sessionStorage.setItem('token', '12345');
// Get item
let token = sessionStorage.getItem('token');
console.log(token); // "12345"
// Remove item
sessionStorage.removeItem('token');
// Clear all items
sessionStorage.clear();

? Example: Storing Objects with JSON

Because storage only handles strings, objects must be converted using JSON.

? View Code Example
const preferences = {
theme: 'dark',
fontSize: 16
};

// Store object as JSON string
localStorage.setItem('prefs', JSON.stringify(preferences));

// Read string and convert back to object
const stored = localStorage.getItem('prefs');
const parsedPrefs = JSON.parse(stored);

console.log(parsedPrefs.theme);   // "dark"
console.log(parsedPrefs.fontSize); // 16

? Live Output & Explanation

? What happens when the code runs?

  • In the localStorage example, the key "username" is saved and can be read on any page from the same origin, even after reloading or reopening the browser.
  • In the sessionStorage example, the key "token" exists only in the currently open tab. Closing that tab clears the value automatically.
  • In the JSON example, the object is first converted to a string with JSON.stringify(), stored, and then converted back with JSON.parse().
  • If localStorage.clear() or sessionStorage.clear() is called, all keys for that storage type are removed for that origin.

? Tips & Best Practices

  • Always use JSON.stringify() for complex data (arrays/objects) and JSON.parse() when reading them back.
  • Use localStorage for user preferences that should persist (theme, language, layout).
  • Use sessionStorage for temporary or sensitive data that should not survive tab close (wizard progress, one-time tokens).
  • Handle storage limits with try...catch; trying to store too much can throw a QuotaExceededError.
  • Never store highly sensitive data like passwords or full authentication tokens in Web Storage.

? Try It Yourself

  • Create a small page that asks for the user’s name once, saves it in localStorage, and greets the user automatically on the next visit.
  • Use sessionStorage to store a temporary token or a step number in a multi-step form, and observe how it resets when the tab is closed.
  • Build an object with user preferences, store it using JSON.stringify(), then read and apply those preferences with JSON.parse() on page load.