Lesson 59 +10 XP

HTML Web Storage

HTML Web Storage

Web Storage lets websites save small pieces of data in your browser. Like leaving notes for yourself so you don't forget!

What is web storage?

With Web Storage, a website can save data on YOUR computer. The data survives refreshing and even closing the browser.

localStorage

localStorage saves data with NO expiration. It stays until you (or the site) clear it.

// Save data
localStorage.setItem("name", "Ada");

// Read data
var name = localStorage.getItem("name");

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

sessionStorage

sessionStorage is like localStorage, but it clears when the tab closes.

sessionStorage.setItem("tabNote", "Still on this tab");

The difference

StorageLasts untilExample use
localStorageUser clears itsaved preferences, scores
sessionStorageTab closesform draft, one-session data

Storing objects

Storage keeps text. To save objects, convert them with JSON.stringify and read them back with JSON.parse:

// Save an object
var user = { name: "Ada", score: 95 };
localStorage.setItem("user", JSON.stringify(user));

// Read it back
var saved = JSON.parse(localStorage.getItem("user"));
console.log(saved.name); // "Ada"

A tiny counter example

// Count how many times you visit
var clicks = localStorage.getItem("clicks") || 0;
clicks++;
localStorage.setItem("clicks", clicks);
document.getElementById("result").innerHTML = "Visits: " + clicks;

Why web storage?

  • No server needed for small data.
  • Faster than cookies for some things.
  • Only your website can read its own storage (privacy!).

Important: don't store secrets!

Anyone can open the browser's developer tools and read localStorage. Never store passwords or secret tokens there!

TL;DR

  • localStorage: data with no expiration.
  • sessionStorage: data until the tab closes.
  • setItem, getItem, removeItem are the tools.
  • Use JSON.stringify/JSON.parse for objects.
  • Never store passwords or secrets in storage!