Web Analytics

Web Storage API

Practical ~15 min read

What is Web Storage?

The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

  • localStorage: Stores data with no expiration date.
  • sessionStorage: Stores data for one session (data is lost when the browser tab is closed).

localStorage Object

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

HTML
CSS
JS

sessionStorage Object

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.

HTML
CSS
JS
Note: Keys and values are always strings. Remember to convert them to other formats if needed (e.g., using JSON.parse() and JSON.stringify() for objects).

Summary

  • setItem(key, value): Add key and value to storage.
  • getItem(key): Retrieve a value by key.
  • removeItem(key): Remove an item by key.
  • clear(): Clear all storage.

Quick Quiz

Which storage object persists data even after the browser is closed?

A
sessionStorage
B
cookieStorage
C
localStorage
D
browserStorage