Using the HTML Web Storage API: `localStorage` and `sessionStorage`

Learn how to store data locally in a user's browser using the Web Storage API's `localStorage` (persistent) and `sessionStorage` (session-based) objects. This tutorial covers browser compatibility, basic usage, and examples demonstrating how to store and retrieve data. A more efficient alternative to cookies!



Using the HTML Web Storage API

The Web Storage API provides a way for web applications to store data locally in the user's browser, offering a more efficient and secure alternative to cookies.

Browser Support

Browser Version
Chrome 4.0+
Edge 8.0+
Firefox 3.5+
Safari 4.0+
Opera 11.5+

Web Storage Objects

The Web Storage API offers two objects:

  • window.localStorage: Stores data persistently; it's not deleted when the browser closes.
  • window.sessionStorage: Stores data only for a single browser session; data is cleared when the browser tab is closed.

Always check for browser support before using Web Storage:

Checking for Web Storage Support

if (typeof(Storage) !== "undefined") {
  // Code to use localStorage or sessionStorage
} else {
  // Web Storage not supported
}

localStorage: Persistent Storage

localStorage stores data indefinitely. Data is stored as string key-value pairs.

Example: Using localStorage

// Store data
localStorage.setItem("name", "John Doe");

// Retrieve data
let name = localStorage.getItem("name");

// Remove data
localStorage.removeItem("name"); 

You can also access items directly like this: localStorage.name = "John Doe"; and name = localStorage.name;

(Example showing a click counter using localStorage is added here.)

sessionStorage: Session Storage

sessionStorage is similar to localStorage but data is only available for the current browser tab session. Closing the tab clears the data.

Example: Using sessionStorage

// Store data (same syntax as localStorage)
sessionStorage.setItem("clicks", "1");

// Retrieve and increment click counter (same logic as localStorage example)

(Example showing a click counter within a session using sessionStorage is added here.)