Skip to content

HTML5 Web Storage

The HTML5 Web Storage API provides a mechanism that allows browsers to securely store key-value pair data on the client side. It's simpler and more intuitive than using Cookies, and has larger storage capacity.

Web storage is divided into two main types:

  • localStorage: Permanent storage. Data persists even if the user closes the browser or restarts the computer, until explicitly deleted. Data is shared across all same-origin (same protocol, domain, port) windows and tabs in the same browser.
  • sessionStorage: Session-level storage. Data is only valid during the current browser session. When the user closes the tab or browser window that created the data, the data is deleted.

Advantages of Web Storage

  • Larger capacity: Typically provides at least 5MB of storage space, far exceeding Cookie's 4KB.
  • More secure: Data is not sent to the server with every HTTP request like Cookies, reducing unnecessary data transfer and security risks.
  • Simpler API: Provides a very simple set of setItem, getItem, removeItem methods.

Using localStorage

The localStorage object is used to store data with no expiration time.

Storing Data with setItem()

javascript
// Store data with key "lastname" and value "Smith"
localStorage.setItem("lastname", "Smith");

// You can also assign directly like a regular object
localStorage.username = "John";

Reading Data with getItem()

javascript
// Read data with key "lastname"
var lastName = localStorage.getItem("lastname");
console.log(lastName); // Output: "Smith"

// Direct property access
console.log(localStorage.username); // Output: "John"

Deleting Data with removeItem()

javascript
// Delete data with key "lastname"
localStorage.removeItem("lastname");

Clearing All Data with clear()

javascript
localStorage.clear();

Note: Web storage can only store strings. If you want to store a JavaScript object, you need to first convert it to a JSON string using JSON.stringify(), and when reading, parse it back using JSON.parse().

javascript
const user = { name: 'Alice', age: 30 };

// Store
localStorage.setItem('user', JSON.stringify(user));

// Read
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.name); // Output: Alice

Using sessionStorage

The sessionStorage object's API is exactly the same as localStorage; the only difference is its lifecycle.

javascript
// Store data in the current session
sessionStorage.setItem("session_id", "12345");

// Read data from the current session
var sessionId = sessionStorage.getItem("session_id");

When you close this browser tab, the session_id data will be automatically cleared. Data in localStorage, however, will be retained.

Content is for learning and research only.