Skip to main content

How to Use Session Storage and Local Storage in JavaScript

Web browsers provide a powerful feature called the Web Storage API that allows you to store key-value pairs directly in the user's browser. This is essential for tasks like remembering a user's preferences, keeping them logged in, or saving application state between page loads.

This guide will teach you how to use the two primary mechanisms of this API: sessionStorage and localStorage. You will learn their shared methods for setting and getting data, and understand the critical difference between them.

The Core Concept: The Web Storage API

Both sessionStorage and localStorage are part of the Web Storage API. They provide a simple way to store data as key-value pairs, where both the key and the value must be strings. They share the same set of methods for interacting with the stored data.

The Key Difference: sessionStorage vs. localStorage

The only difference between the two is their persistence and scope:

  • sessionStorage:

    • Persistence: The data is cleared when the browser tab is closed. It only lasts for the duration of the page session.
    • Scope: The data is unique to each browser tab. If a user has two tabs open to your site, they will have two separate session storages.
  • localStorage:

    • Persistence: The data persists even after the browser is closed and reopened. It has no expiration date and is only cleared if the user manually clears their browser cache or you programmatically remove it.
    • Scope: The data is shared across all tabs and windows from the same origin (domain).

How to Set and Get Storage Items

The methods for setting and getting data are identical for both sessionStorage and localStorage.

For example, we want to save a user's name and then retrieve it later. The solution uses the .setItem() and .getItem() methods.

Example with sessionStorage:

sessionStorage
// --- Using sessionStorage ---
// Store a value
sessionStorage.setItem('username', 'Alice');

// Retrieve the value
const sessionUser = sessionStorage.getItem('username');
console.log('Session User:', sessionUser);
// Output: "Alice"

Example with localStorage:

localStorage
// --- Using localStorage ---
// Store a value
localStorage.setItem('theme', 'dark');

// Retrieve the value
const savedTheme = localStorage.getItem('theme');
console.log('Saved Theme:', savedTheme);
// Output: "dark"
note

If you try to get an item that doesn't exist, both methods will return null.

Working with Objects and Arrays (Using JSON)

The Web Storage API can only store strings. If you want to store a JavaScript object or array, you must first serialize it into a JSON string using JSON.stringify(), and then parse it back into an object with JSON.parse() upon retrieval.

const userSettings = {
theme: 'dark',
notifications: true,
username: 'Alice',
};

// 1. Stringify the object before saving it
localStorage.setItem('userSettings', JSON.stringify(userSettings));

// 2. Retrieve the string
const settingsString = localStorage.getItem('userSettings');

// 3. Parse the string back into an object
const parsedSettings = JSON.parse(settingsString);

console.log(parsedSettings);
// Output: { theme: 'dark', notifications: true, username: 'Alice' }
console.log(parsedSettings.theme);
// Output: "dark"

This is the standard and only correct way to store complex data structures in Web Storage.

How to Remove Storage Items

You can remove items from storage in two ways:

  • .removeItem(key): Removes a single, specific item.
  • .clear(): Removes all items from that origin's storage.
localStorage.setItem('theme', 'dark');
localStorage.setItem('username', 'Alice');

// Remove a single item
localStorage.removeItem('theme');
console.log(localStorage.getItem('theme'));
// Output: null

// Remove all remaining items
localStorage.clear();
console.log(localStorage.getItem('username'));
// Output: null

Conclusion: Which One Should You Use?

The choice between sessionStorage and localStorage depends entirely on your persistence requirements.

  • Use sessionStorage for data that is relevant only to the current browser tab and should be discarded when the tab is closed (e.g., data for a multi-step form).
  • Use localStorage for data that needs to be saved across browser sessions and shared between tabs (e.g., a user's login status, site preferences like a theme).

By understanding this key difference, you can choose the right tool to manage client-side data effectively.