Skip to content

Session Storage

This lesson explains Session Storage with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Session Storage API Overview

The HTML5 Session Storage API provides temporary key-value storage that exists only for the lifetime of a browser tab or window. Unlike Local Storage, Session Storage is automatically cleared when the browser tab is closed.

Session Storage is commonly used for temporary form data, shopping cart drafts, multi-step wizards, authentication flow state, page-specific user preferences, temporary filters, and session-specific application data.

Feature Description
API Name Session Storage API
Main Object window.sessionStorage
Storage Type Key-Value pairs
Persistence Until browser tab is closed
Scope Per browser tab or window
Typical Size Approximately 5 MB per origin

Basic Session Storage Example

// Save data

sessionStorage.setItem(
  "username",
  "john"
);

// Read data

const username =
  sessionStorage.getItem(
    "username"
  );

console.log(username);

Data stored in Session Storage remains available while the current browser tab is open.

How Session Storage Works

Step Description Example
Store Data Save key-value pair. setItem()
Retrieve Data Read stored value. getItem()
Update Value Overwrite existing key. setItem()
Delete Value Remove one key. removeItem()
Clear Storage Remove every key. clear()
Tab Closed Storage automatically disappears. Automatic cleanup

Session Storage Methods

Method Description Example
setItem() Stores a value. setItem(key, value)
getItem() Returns stored value. getItem(key)
removeItem() Deletes one key. removeItem(key)
clear() Removes all data. clear()
key() Returns key by index. key(index)
length Returns number of items. sessionStorage.length

Store a String

sessionStorage.setItem(
  "theme",
  "dark"
);

console.log(
  sessionStorage.getItem("theme")
);

Session Storage stores values as strings.

Store an Object

const user =
  {
    id: 101,
    name: "Alice",
    role: "Admin"
  };

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

const storedUser =
  JSON.parse(
    sessionStorage.getItem("user")
  );

console.log(storedUser);

Objects must be converted to JSON before storing and parsed after reading.

Store an Array

const colors =
  [
    "Red",
    "Blue",
    "Green"
  ];

sessionStorage.setItem(
  "colors",
  JSON.stringify(colors)
);

const storedColors =
  JSON.parse(
    sessionStorage.getItem("colors")
  );

console.log(storedColors);

Arrays are stored the same way as JavaScript objects.

Update Existing Data

sessionStorage.setItem(
  "language",
  "English"
);

sessionStorage.setItem(
  "language",
  "French"
);

console.log(
  sessionStorage.getItem("language")
);

Calling setItem() with an existing key replaces its value.

Remove One Item

sessionStorage.removeItem(
  "language"
);

Use removeItem() to delete a single entry.

Clear Session Storage

sessionStorage.clear();

The clear() method removes every stored value for the current origin in the active browser tab.

Loop Through Session Storage

for (
  let index = 0;
  index < sessionStorage.length;
  index++
) {
  const key =
    sessionStorage.key(index);

  console.log(
    key,
    sessionStorage.getItem(key)
  );
}

The length property and key() method allow you to iterate through stored values.

Save Form Data Automatically

const input =
  document.querySelector("#email");

input.value =
  sessionStorage.getItem("email") || "";

input.addEventListener(
  "input",
  () => {
    sessionStorage.setItem(
      "email",
      input.value
    );
  }
);

This technique preserves partially completed forms while users refresh the page.

Multi-Step Form Example

sessionStorage.setItem(
  "currentStep",
  "2"
);

const currentStep =
  sessionStorage.getItem(
    "currentStep"
  );

console.log(
  "Resume wizard at step:",
  currentStep
);

Multi-page forms often use Session Storage to remember the current step.

Temporary Shopping Cart

const cart =
  [
    "Laptop",
    "Keyboard"
  ];

sessionStorage.setItem(
  "cart",
  JSON.stringify(cart)
);

Temporary carts or draft orders are good candidates for Session Storage because they disappear after the browsing session ends.

Feature Detection

if ("sessionStorage" in window) {
  console.log(
    "Session Storage supported."
  );
} else {
  console.log(
    "Session Storage unavailable."
  );
}

Feature detection helps ensure compatibility across different browsers and browsing modes.

Local Storage vs Session Storage

Feature Local Storage Session Storage
Lifetime Persistent until removed. Removed when tab closes.
Scope Shared across tabs. One browser tab only.
Best Use User preferences. Temporary session data.
Storage Limit About 5 MB. About 5 MB.
Automatic Cleanup No. Yes.

Security Considerations

// Avoid storing secrets

sessionStorage.setItem(
  "theme",
  "dark"
);

// Avoid

sessionStorage.setItem(
  "accessToken",
  "very-secret-token"
);
  • Do not store passwords or authentication tokens.
  • Session Storage is accessible to JavaScript.
  • XSS vulnerabilities can expose stored values.
  • Store only temporary, non-sensitive information.
  • Clear data after logout or sensitive workflows.

Common Session Storage Use Cases

  • Temporary form drafts.
  • Multi-step registration forms.
  • Wizard progress.
  • Shopping cart drafts.
  • Temporary search filters.
  • Current tab state.
  • Recently viewed data during one session.
  • UI preferences that should disappear after closing the tab.

Session Storage Best Practices

  • Store only temporary application state.
  • Use JSON for objects and arrays.
  • Remove unused data promptly.
  • Check browser support before using the API.
  • Keep stored values small.
  • Use meaningful key names.
  • Handle missing values safely.
  • Use Local Storage instead when persistence is required.

Common Session Storage Mistakes

  • Assuming data survives after the tab closes.
  • Storing sensitive user information.
  • Forgetting to convert objects using JSON.
  • Not handling missing keys.
  • Using Session Storage as a database.
  • Exceeding browser storage limits.
  • Ignoring XSS risks.
  • Using Session Storage for long-term preferences.

Key Takeaways

  • Session Storage stores temporary key-value data.
  • Data is available only while the current browser tab remains open.
  • Objects and arrays require JSON serialization.
  • Use Session Storage for temporary application state.
  • Never store passwords or sensitive authentication data.
  • Choose Local Storage when long-term persistence is required.

Pro Tip

Think of Session Storage as a temporary notebook for a single browser tab. It is ideal for preserving user progress during the current session but is automatically cleaned up when the tab closes, making it a safer choice for temporary state than persistent storage.