HTML Session Storage

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples + 3 Try It
sessionStorage

Introduction

Session Storage is part of the Web Storage API. It lets you save simple key-value data in the browser for as long as the current tab stays open. Unlike localStorage, which persists across browser restarts, sessionStorage is cleared when the user closes the tab.

Use it for temporary state: wizard steps, form drafts, filters on a listing page, or anything you do not need to share with other tabs. This tutorial covers the API, comparisons with other storage options, and plain HTML Try It demos.

What You’ll Learn

01

setItem

Save strings.

02

getItem

Read values.

03

removeItem

Delete one key.

04

clear

Wipe tab data.

05

Per tab

Not shared.

06

vs local

When to pick.

What Is Session Storage?

Session Storage is a browser mechanism for storing key-value pairs as strings. Each key maps to one value for the lifetime of the page session in that tab.

A page session:

  • Starts when you open a tab and visit a page.
  • Survives reloads and back/forward navigation in the same tab.
  • Ends when the tab or browser window is closed.
  • Is isolated — other tabs have their own separate sessionStorage.
💡
Beginner Tip

Data is scoped to origin (protocol + domain + port) and tab. Two tabs on example.com do not see each other’s sessionStorage values.

How Does Session Storage Work?

Browsers expose a global sessionStorage object in JavaScript. It behaves like a simple dictionary:

  • Keys and values are always strings.
  • Storage is synchronous — reads and writes block the main thread briefly (fine for small data).
  • Access is limited to pages from the same origin in that tab.
  • It is not sent to the server automatically (unlike cookies).

For large structured data or offline databases, use IndexedDB instead. For tiny strings that must persist forever across visits, use localStorage.

Using Session Storage

The sessionStorage object provides four essential methods:

  • sessionStorage.setItem(key, value) — stores a string under key.
  • sessionStorage.getItem(key) — returns the string or null if missing.
  • sessionStorage.removeItem(key) — deletes one entry.
  • sessionStorage.clear() — removes every key in this tab.

You can also use bracket syntax: sessionStorage['theme'] = 'dark' (still stores strings only).

Helpful properties:

  • sessionStorage.length — number of keys.
  • sessionStorage.key(index) — name of the key at position index.

Storing and Retrieving Data

js
// Storing data
sessionStorage.setItem('username', 'JohnDoe');

// Retrieving data
var username = sessionStorage.getItem('username');
console.log(username); // JohnDoe

// Missing key returns null
console.log(sessionStorage.getItem('missing')); // null

Storing objects (JSON)

js
var user = { name: 'Jane', score: 42 };

sessionStorage.setItem('user', JSON.stringify(user));

var saved = JSON.parse(sessionStorage.getItem('user'));
console.log(saved.name); // Jane

Removing Data

Delete one key or wipe the entire session store for the tab:

js
// Remove one key
sessionStorage.removeItem('username');

// Remove everything in this tab's sessionStorage
sessionStorage.clear();

Call removeItem when a user logs out of a single-page flow. Call clear sparingly—it deletes all keys your app stored in that tab.

Session Storage vs localStorage

FeaturesessionStoragelocalStorage
LifetimeUntil tab closesUntil cleared manually
Shared across tabsNo (per tab)Yes (same origin)
Survives reloadYesYes
Typical useWizard state, tab draftsTheme, login token, prefs

Common Pitfalls

  1. Data persistence — sessionStorage is not permanent. Closing the tab deletes everything. Do not rely on it for long-term preferences.
  2. Storage limit — roughly 5 MB per origin. Very large strings can throw QuotaExceededError.
  3. Cross-tab communication — each tab has its own store. Use localStorage plus the storage event, or BroadcastChannel, to sync across tabs.
  4. Strings only — numbers become strings ("42"). Objects need JSON.stringify.
  5. Not for secrets — any script on your page can read sessionStorage. Never store passwords or API keys here.
  6. Private browsing — some browsers use in-memory storage that clears when the private session ends.

⚡ Quick Reference

TaskCode
SavesessionStorage.setItem('key', 'value')
ReadsessionStorage.getItem('key')
Delete onesessionStorage.removeItem('key')
Delete allsessionStorage.clear()
Count keyssessionStorage.length
Store objectsetItem('k', JSON.stringify(obj))
Save
setItem()

Write

Read
getItem()

Read

Scope
one tab

Isolated

Type
string

Values

Examples Gallery

Five short examples from basic save/read to a full HTML page. Try It Yourself demos use plain HTML with no CSS so you can focus on the API.

Example 1 — Save and Read a String

js
sessionStorage.setItem('username', 'JohnDoe');
var name = sessionStorage.getItem('username');
console.log(name); // JohnDoe
Try It Yourself

How It Works

setItem overwrites an existing key with the same name.

Example 2 — Store an Object with JSON

js
var cart = { items: 2, total: 19.99 };
sessionStorage.setItem('cart', JSON.stringify(cart));

var loaded = JSON.parse(sessionStorage.getItem('cart'));
console.log(loaded.total); // 19.99
Try It Yourself

How It Works

Always wrap JSON.parse in try/catch if data might be corrupted.

Example 3 — Remove One Key

js
sessionStorage.setItem('temp', 'draft');
sessionStorage.removeItem('temp');
console.log(sessionStorage.getItem('temp')); // null
Try It Yourself

How It Works

removeItem on a missing key does not throw an error.

Example 4 — List All Keys

js
for (var i = 0; i < sessionStorage.length; i++) {
  var key = sessionStorage.key(i);
  console.log(key, sessionStorage.getItem(key));
}
Try It Yourself

How It Works

Useful for debugging what your app stored in the current tab.

Example 5 — Example Usage (Full Page)

Save and load a user name — from the reference tutorial, improved with auto-load on open:

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Session Storage Example</title>
</head>
<body>
  <h1>Session Storage Example</h1>
  <input type="text" id="input" placeholder="Enter your name">
  <button id="save">Save</button>
  <button id="load">Load</button>
  <p id="result"></p>

  <script>
    document.getElementById('save').onclick = function () {
      sessionStorage.setItem('userName', document.getElementById('input').value);
    };

    document.getElementById('load').onclick = function () {
      var userName = sessionStorage.getItem('userName');
      document.getElementById('result').textContent =
        userName ? 'Hello, ' + userName : 'No name saved';
    };
  </script>
</body>
</html>
Try It Yourself

How It Works

Reload the Try It page after saving—the name remains until you close the tab.

🚀 Common Use Cases

  • Multi-step forms — remember wizard step or partial answers.
  • Tab-specific filters — sort order that should not affect other tabs.
  • SPA navigation state — scroll position or panel selection until tab closes.
  • Shopping session — temporary cart before checkout (not long-term).
  • A/B test bucket — keep user in same variant for this visit.
  • Debug flags — verbose logging toggle for current session only.

🧠 How sessionStorage Works (Step by Step)

1

User opens tab

Browser creates empty sessionStorage for this tab.

Start
2

setItem(key, value)

Your script saves a string.

Write
3

Reload / navigate

Data stays in the same tab.

Persist
4

getItem(key)

Page reads saved state on load.

Read
=

Tab closed

All sessionStorage for that tab is cleared.

📝 Notes

  • sessionStorage is not a replacement for server-side sessions or secure auth tokens.
  • Values are visible in DevTools → Application → Session Storage.
  • Incognito/private windows may discard storage when the session ends.
  • Third-party iframes on other origins cannot read your sessionStorage.
  • For cross-tab sync, use localStorage and the storage event.
  • For large offline data, use IndexedDB.

Universal Browser Support

sessionStorage is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. It is part of the HTML5 Web Storage specification.

Baseline · Since HTML

sessionStorage API

sessionStorage is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. It is part of the HTML5 Web Storage specification.

98% Modern browser support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
sessionStorage API Excellent

Bottom line: Safe to use in all current projects. Feature-detect with typeof sessionStorage !== 'undefined' in very old environments.

💡 Best Practices

✅ Do

  • Use sessionStorage for temporary, tab-scoped state
  • Serialize objects with JSON.stringify / JSON.parse
  • Pick clear key names (checkoutStep, draftNote)
  • Remove keys when data is no longer needed
  • Handle null from getItem before using values
  • Keep stored strings small (under a few KB each)

❌ Don’t

  • Store passwords, tokens, or PCI data
  • Assume data survives after the tab closes
  • Expect other tabs to read the same sessionStorage
  • Store huge JSON blobs (use IndexedDB instead)
  • Trust sessionStorage values without validation
  • Use sessionStorage when localStorage persistence is required

Conclusion

Session Storage is a useful tool for storing data temporarily during a web session. It provides a straightforward way to manage tab-scoped state with setItem, getItem, removeItem, and clear.

Choose sessionStorage when data should disappear with the tab. Choose localStorage for long-lived preferences, or IndexedDB for structured offline data. Try the demos below to see the API in action.

Key Takeaways

Knowledge Unlocked

Five things to remember about sessionStorage

Use these points when picking client-side storage.

5
Core concepts
⏱️ 02

Tab lifetime

Not forever.

Duration
📝 03

Strings

JSON helps.

Type
🔄 04

Reload OK

Data stays.

Persist
🔒 05

Not secure

No secrets.

Safety

❓ Frequently Asked Questions

sessionStorage is part of the Web Storage API. It stores key-value string pairs for the current browser tab. Data survives page reloads but is cleared when the tab or window is closed.
localStorage persists until you clear it manually or the user clears site data—it is shared across tabs of the same origin. sessionStorage is per tab and lasts only for that tab's session.
Call sessionStorage.setItem('key', 'value'). Both key and value must be strings. Retrieve with sessionStorage.getItem('key'), which returns null if the key does not exist.
Yes. Reloading the page in the same tab keeps sessionStorage data. Opening a new tab starts a fresh, empty sessionStorage for that tab.
Only strings are stored directly. Serialize objects with JSON.stringify(obj) before setItem, and parse with JSON.parse(sessionStorage.getItem('key')) when reading.
Browsers typically allow about 5 MB per origin for sessionStorage (similar to localStorage). Storing very large strings may throw a QuotaExceededError.
Did you know?

Opening a link with target="_blank" creates a new tab with fresh sessionStorage, even on the same site. Duplicate tabs do not copy session data—only localStorage is shared across tabs.

Practice sessionStorage in the editor

Save a name, reload the page, and see it persist until you close the tab—plain HTML, no CSS required.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful