Rajesh DhimanRajesh Dhiman
Free AuditServicesCase StudiesProjectsBooksBlogResourcesAboutContact
Book a CallRD
  1. Home
  2. Blog
  3. Web Storage APIs Explained: localStorage, sessionStorage, and IndexedDB

Web Storage APIs Explained: localStorage, sessionStorage, and IndexedDB

RDRajesh Dhiman
November 18, 2024
5 min read
web storage APIs
localStorage vs sessionStorage
IndexedDB tutorial
browser storage JavaScript
IndexedDB example
client-side storage

Imagine This...

You're building a to-do list app. Your user painstakingly enters their tasks for the day, hits refresh, and—poof!—all the tasks disappear. Frustrating, right? This is where Web Storage APIs come in to save the day. These tools let you store data in the browser so your app can remember the user's tasks, preferences, and more—even if they close the tab or browser.

In this guide, we’ll explore localStorage, sessionStorage, and IndexedDB, breaking down when and how to use each. By the end, you'll have the knowledge to build apps that feel smarter and more responsive.


Introduction: Your App’s Filing Cabinet

Think of your app’s data like a collection of notes in a filing cabinet. Some notes (like user preferences) need to stay forever, while others (like a shopping cart) should vanish when you close the app. Web Storage APIs are the tools that help you organize this "filing cabinet" with efficiency and clarity.


Overview of Web Storage APIs

Let’s break down the three main Web Storage APIs: localStorage, sessionStorage, and IndexedDB.

1. localStorage: The Persistent Filing Cabinet

  • What it is: localStorage is a simple key-value storage mechanism that persists even after the browser is closed.
  • Use case: Perfect for storing user preferences, theme settings, or other data that doesn’t need to expire.

Code Example:

// Save data to localStorage
localStorage.setItem('theme', 'dark');

// Retrieve data from localStorage
const theme = localStorage.getItem('theme');
console.log(theme); // Output: 'dark'

// Remove data
localStorage.removeItem('theme'); 

📄 Documentation: localStorage


2. sessionStorage: The Temporary Sticky Note

  • What it is: sessionStorage is similar to localStorage but only lasts for the duration of the browser session (until the tab is closed).
  • Use case: Ideal for temporary data like form inputs or progress tracking that doesn’t need to persist.

Code Example:

// Save data to sessionStorage
sessionStorage.setItem('sessionID', 'abc123');

// Retrieve data from sessionStorage
const sessionID = sessionStorage.getItem('sessionID');
console.log(sessionID); // Output: 'abc123'

// Clear sessionStorage
sessionStorage.clear(); 

📄 Documentation: sessionStorage


3. IndexedDB: The Database for the Browser

  • What it is: IndexedDB is a low-level API for storing large amounts of structured data. It allows you to store data in key-value pairs and supports advanced querying.
  • Use case: Best for offline applications, large datasets, or complex data structures.

Code Example:

// Open a database
const request = indexedDB.open('MyDatabase', 1);

request.onsuccess = function () {
  const db = request.result;
  console.log('Database opened successfully:', db);
};

request.onerror = function () {
  console.error('Database failed to open');
};

// Create an object store
request.onupgradeneeded = function () {
  const db = request.result;
  db.createObjectStore('notes', { keyPath: 'id', autoIncrement: true });
};

// Add data to the database
request.onsuccess = function () {
  const db = request.result;
  const transaction = db.transaction('notes', 'readwrite');
  const store = transaction.objectStore('notes');
  store.add({ title: 'Note 1', content: 'This is a note.' });
}; 

📄 Documentation: IndexedDB


Choosing the Right Web Storage API

  • localStorage:

    • Best For: Long-term storage, such as themes or user settings.
    • Limitations: Limited to 5MB; synchronous operations can block the UI.
  • sessionStorage:

    • Best For: Temporary storage, such as session-specific data like form inputs.
    • Limitations: Limited to 5MB; data clears when the browser tab is closed.
  • IndexedDB:

    • Best For: Complex and large datasets, such as offline applications or large collections of structured data.
    • Limitations: Has a higher learning curve and uses asynchronous operations.

Practical Example: Building a Mini App Using All APIs

Let’s create a simple notes app that uses all three storage APIs.

Features:

  1. sessionStorage: Temporarily save notes before they’re submitted.
  2. localStorage: Save user preferences like dark mode.
  3. IndexedDB: Store submitted notes permanently.

HTML:

<body>
  <label>
    Dark Mode: 
    <input type="checkbox" id="darkModeToggle" />
  </label>
  <textarea id="noteInput" placeholder="Write a note..."></textarea>
  <button id="saveNote">Save Note</button>
  <div id="notesList"></div>
  <script src="app.js"></script>
</body> 

JavaScript (app.js):

// 1. Toggle dark mode using localStorage
const darkModeToggle = document.getElementById('darkModeToggle');
darkModeToggle.checked = localStorage.getItem('darkMode') === 'true';

darkModeToggle.addEventListener('change', () => {
  localStorage.setItem('darkMode', darkModeToggle.checked);
  document.body.style.backgroundColor = darkModeToggle.checked ? '#333' : '#fff';
});

// 2. Save draft notes using sessionStorage
const noteInput = document.getElementById('noteInput');
noteInput.value = sessionStorage.getItem('draftNote') || '';

noteInput.addEventListener('input', () => {
  sessionStorage.setItem('draftNote', noteInput.value);
});

// 3. Save notes permanently using IndexedDB
const request = indexedDB.open('NotesApp', 1);

request.onupgradeneeded = function () {
  const db = request.result;
  db.createObjectStore('notes', { keyPath: 'id', autoIncrement: true });
};

document.getElementById('saveNote').addEventListener('click', () => {
  const db = request.result;
  const transaction = db.transaction('notes', 'readwrite');
  const store = transaction.objectStore('notes');
  store.add({ content: noteInput.value });
  sessionStorage.removeItem('draftNote');
  noteInput.value = '';
  displayNotes();
});

// Display saved notes
function displayNotes() {
  const db = request.result;
  const transaction = db.transaction('notes', 'readonly');
  const store = transaction.objectStore('notes');
  const requestAll = store.getAll();

  requestAll.onsuccess = function () {
    const notesList = document.getElementById('notesList');
    notesList.innerHTML = requestAll.result
      .map(note => `<p>${note.content}</p>`)
      .join('');
  };
} 

Conclusion: Try Web Storage in Your Next Project

Each Web Storage API has unique strengths. localStorage and sessionStorage are easy to use for small projects, while IndexedDB shines for complex applications. By understanding these tools, you can build faster, more efficient, and offline-capable web apps.


If you enjoyed this article, consider supporting my work:

  • Buy me a coffee
  • Book a call for mentorship or career advice
  • Follow me on Twitter
  • Connect on LinkedIn
Free field guide

Ship AI features that survive real traffic

Start from the failure modes, choose the smallest architecture that holds up, and instrument the path before you scale it.

No spam, unsubscribe anytime. You will also get instant access on the next screen.

Share this article

TwitterLinkedInFacebook
Buy Me a Coffee
Support my work

If you found this article helpful, consider buying me a coffee to support more content like this.

Buy a Coffee
RD

Written by

Rajesh Dhiman

Founder of Eunix Tech · Author · AI Systems Engineer

I've been building software for over a decade and I'm the founder of Eunix Tech, a software consultancy. I've written two books, the Vibe Coding Survival Guide and the Frontend Interview Guide, plus a set of practical engineering checklists. I spent 4 years at Alloy Automation building integrations for companies like Amazon and Best Buy, and I'm a top-rated mentor on Codementor (5.0 from 26 reviews). Today I rescue failing AI projects, audit AI-generated and no-code apps, and build production-grade automation that delivers measurable ROI.

AboutBooksEunix TechLinkedInGitHubXCodementor

Related Articles

Migrating a Bubble App to Next.js: When, How, Cost and Risk
Migrating a Bubble App to Next.js: When, How, Cost and Risk
10/16/2026

Thinking of moving a Bubble app to Next.js? Here is when it makes sense, the migration steps, what drives cost and timeline, and the risks to plan for.

AI Agent Development Services: How to Build Agents That Actually Work in Production
AI Agent Development Services: How to Build Agents That Actually Work in Production
10/14/2026

Explore AI agent development services for building reliable, production-ready AI agents. Learn about architecture, integrations, security, testing, deployment, and costs.

AI Automation Agency vs In-House Development: Which Approach Is Right for Your Business?
AI Automation Agency vs In-House Development: Which Approach Is Right for Your Business?
10/14/2026

Compare an AI automation agency with in-house development. Learn about costs, services, benefits, risks, timelines, and how to choose the right approach.

On this page

  • Imagine This...
  • Introduction: Your App’s Filing Cabinet
  • Overview of Web Storage APIs
  • 1. localStorage: The Persistent Filing Cabinet
  • 2. sessionStorage: The Temporary Sticky Note
  • 3. IndexedDB: The Database for the Browser
  • Choosing the Right Web Storage API
  • Practical Example: Building a Mini App Using All APIs
  • Features:
  • Conclusion: Try Web Storage in Your Next Project
Free field guide

Ship AI features that survive real traffic

Start from the failure modes, choose the smallest architecture that holds up, and instrument the path before you scale it.

No spam, unsubscribe anytime. You will also get instant access on the next screen.

App failing in production or automation that keeps breaking? Book a technical diagnostic →

Rajesh DhimanRajesh Dhiman

© 2026 Eunix Tech

Tickoff, a client link for freelancers (opening 17 Nov)

Free AuditServicesCase StudiesProjectsBooksBlogResourcesMy StackAboutContact