Codectionary / Developer documentation / JavaScript

localStorage and sessionStorage

localStorage and sessionStorage let you store key-value data directly in the browser, using the same simple API. localStorage persists indefinitely, even after closing the browser, while sessionStorage clears when the tab is closed. Both only store strings - objects must be converted with JSON.stringify() and JSON.parse().

Syntax

localStorage.setItem(key, value)
localStorage.getItem(key)

Examples

Basic Storage Operations

Storing, retrieving, and removing simple string values.

localStorage.setItem("username", "alice");
console.log(localStorage.getItem("username")); // "alice"

localStorage.removeItem("username");
console.log(localStorage.getItem("username")); // null

localStorage.setItem("theme", "dark");
localStorage.setItem("fontSize", "16");
localStorage.clear(); // removes everything

Storing Objects with JSON

localStorage only stores strings, so objects need to be serialized.

const userPrefs = { theme: "dark", fontSize: 16, notifications: true };

localStorage.setItem("preferences", JSON.stringify(userPrefs));

const stored = JSON.parse(localStorage.getItem("preferences"));
console.log(stored.theme); // "dark"
console.log(typeof stored); // "object" - properly restored, not just a string

localStorage vs sessionStorage

Choosing the right storage based on how long data should persist.

// Persists across browser restarts, until explicitly cleared
localStorage.setItem("rememberedEmail", "user@example.com");

// Cleared automatically when the tab/browser is closed
sessionStorage.setItem("currentStep", "3");

// Both share the identical API - only the lifetime differs

Best practices

  • Always wrap JSON.parse() calls on stored data in a try/catch, in case the stored value is missing or corrupted
  • Use sessionStorage for temporary, per-tab data (like a multi-step form's progress), and localStorage for data that should persist long-term
  • Never store sensitive information (passwords, tokens, personal data) in localStorage - it is accessible to any JavaScript running on the page, including malicious scripts
  • Remember storage is per-origin (protocol + domain + port) and has a size limit (typically around 5-10MB) - it is not a substitute for a real database

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation