LocalStorage vs. SessionStorage: A Deep Dive

Category: Advanced JavaScript | Published on: by Dr. Talib

The Web Storage API provides a simple way for web applications to store key/value pairs locally within the user's browser. It offers two mechanisms for this: `localStorage` and `sessionStorage`. While they have an identical API, their behavior and use cases are fundamentally different.

This guide will give you a clear understanding of each, so you can choose the right tool for the job.


The Web Storage API

Both `localStorage` and `sessionStorage` are properties of the global `window` object. They allow you to store data as strings. If you want to store a JavaScript object, you must first convert it to a string using `JSON.stringify()`, and then parse it back with `JSON.parse()` upon retrieval.

The API for both is the same:

  • setItem(key, value): Adds a key/value pair.
  • getItem(key): Retrieves the value for a given key.
  • removeItem(key): Removes a specific key/value pair.
  • clear(): Removes all items.
  • key(index): Retrieves the key at a given numerical index.
  • length: A property that returns the number of items stored.

LocalStorage: Persistent Storage

localStorage stores data with no expiration date. The data will persist even after the user closes the browser window or reboots their computer. It remains available until it is explicitly cleared by the user (via browser settings) or by your web application.

When to Use LocalStorage:

Use it for data you want to remember across browsing sessions.

  • Saving user preferences, like a "dark mode" or "light mode" theme choice.
  • Storing a JWT token for persistent login.
  • Caching application settings or non-critical data to improve performance.

Example: Saving a Theme Preference

// --- Saving the preference ---
const themeToggle = document.getElementById('theme-toggle');

themeToggle.addEventListener('click', () => {
  document.body.classList.toggle('dark-mode');
  
  // Save the current state to localStorage
  if (document.body.classList.contains('dark-mode')) {
    localStorage.setItem('theme', 'dark');
  } else {
    localStorage.setItem('theme', 'light');
  }
});

// --- Applying the preference on page load ---
const savedTheme = localStorage.getItem('theme');

if (savedTheme === 'dark') {
  document.body.classList.add('dark-mode');
}

SessionStorage: Temporary, Session-Only Storage

sessionStorage stores data for one session only. The data is lost when the browser tab is closed. If you open the same website in a new tab, it gets a new, separate session storage.

When to Use SessionStorage:

Use it for temporary data that should be forgotten once the user leaves.

  • Storing data in a multi-step form, so the user doesn't lose their input if they accidentally refresh the page.
  • Keeping track of the state of a single-page application for the current visit.
  • Storing temporary information that shouldn't leak between tabs.

Example: Saving Form Data

// --- Saving input as the user types ---
const formInput = document.getElementById('user-comment');

formInput.addEventListener('input', (e) => {
  sessionStorage.setItem('savedComment', e.target.value);
});

// --- Restoring the data on page load ---
const savedComment = sessionStorage.getItem('savedComment');

if (savedComment) {
  formInput.value = savedComment;
}

Security Note: Both `localStorage` and `sessionStorage` are accessible via JavaScript on the page. They are not secure for storing sensitive information like passwords or credit card numbers, as they are vulnerable to cross-site scripting (XSS) attacks.

LocalStorage vs. SessionStorage: The Key Differences

Feature LocalStorage SessionStorage
Persistence Persists until explicitly deleted. Survives browser restarts. Data is cleared when the browser tab is closed.
Scope Shared across all tabs and windows from the same origin. Scoped to a single browser tab. Each tab has its own storage.
Capacity Around 5-10 MB (browser dependent). Around 5 MB (browser dependent).
Common Use Case User preferences, long-term settings. Temporary form data, single-session state.

Conclusion

The choice between `localStorage` and `sessionStorage` boils down to one simple question: "Do I need this data to still be here the next time the user visits?"

  • If the answer is yes, use localStorage.
  • If the answer is no, use sessionStorage.

By understanding this fundamental difference, you can leverage the Web Storage API effectively to create more robust and user-friendly web applications.

Use our Live HTML Viewer to test how data persists (or doesn't) with localStorage and sessionStorage!