Skip to content

HTML Local Storage

HTML Web Storage (LocalStorage and SessionStorage)

Section titled “HTML Web Storage (LocalStorage and SessionStorage)”

Web Storage allows web applications to store data locally within the user’s browser, offering advantages over traditional cookies.

Web Storage provides mechanisms for web applications to store key/value pairs locally within the user’s browser.

Advantages over Cookies:

  • Larger Capacity: Web Storage offers significantly more storage space (typically 5-10MB per origin) compared to cookies (around 4KB).
  • Not Sent with HTTP Requests: Data stored in Web Storage is not automatically sent to the server with every HTTP request, improving performance and security compared to cookies.
  • Simpler API: Provides straightforward methods (setItem, getItem, removeItem) for data manipulation.

Web Storage is domain-specific. Data stored by pages from one origin (protocol, hostname, port) is isolated and cannot be accessed by pages from another origin.

Web Storage (both LocalStorage and SessionStorage) is supported by all major modern web browsers.

Web Storage provides two main objects for storing data on the client:

  • window.localStorage: Stores data with no expiration date. Data persists even after the browser window is closed and reopened.
  • window.sessionStorage: Stores data for one session only. Data is cleared when the browser tab or window is closed.

Before using Web Storage, you can check for browser support:

if (typeof(Storage) !== 'undefined') {
// Web Storage is supported. You can use localStorage and sessionStorage.
console.log('Web Storage supported!');
} else {
// Sorry! No Web Storage support..
console.log('Web Storage is not supported by this browser.');
}

Use localStorage for data that needs to persist across browser sessions, such as user preferences or offline application data.

Example:

// Get the element to display results
const resultElement = document.getElementById('result');
// Store data: Set a key/value pair
localStorage.setItem('username', 'JohnDoe');
localStorage.setItem('theme', 'dark');
// Retrieve data: Get the value associated with a key
const username = localStorage.getItem('username');
resultElement.innerHTML = `Username retrieved: ${username}<br>`;
// You can also access items like object properties (less recommended if keys might clash with Object prototype properties)
localStorage.userLevel = 'admin';
resultElement.innerHTML += `User level: ${localStorage.userLevel}<br>`;
// Remove data: Delete a specific key/value pair
localStorage.removeItem('theme');
// Check if an item exists
if (localStorage.getItem('theme') === null) {
resultElement.innerHTML += 'Theme has been removed.<br>';
}
// Clear all data: Remove all items stored in localStorage for this origin
// localStorage.clear();
// Iterate over stored items
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
console.log(`Key: ${key}, Value: ${value}`);
}
Important: Web Storage only stores strings. If you need to store objects or arrays, use JSON.stringify() before saving and JSON.parse() after retrieving. Numbers will also be stored as strings, so convert them using Number() or parseInt()/parseFloat() if needed for calculations.

Example: Storing and Retrieving an Object

const userSettings = {
theme: 'dark',
notifications: true,
fontSize: 16
};
// Store the object (as a JSON string)
localStorage.setItem('settings', JSON.stringify(userSettings));
// Retrieve the object (parse the JSON string)
const retrievedSettings = JSON.parse(localStorage.getItem('settings'));
if (retrievedSettings) {
console.log('Retrieved theme:', retrievedSettings.theme); // Output: dark
}

Use sessionStorage for temporary data related to the current browser session, like user input in a multi-step form or the current state of a single-page application.

The API for sessionStorage is identical to localStorage (setItem, getItem, removeItem, clear, key, length), but the data only lasts until the tab/window is closed.

Example: Tracking session activity

// Get the element to display results
const sessionResultElement = document.getElementById('sessionResult');
// Check if a session counter exists, initialize if not
let visitCount = sessionStorage.getItem('pageVisits');
if (visitCount) {
visitCount = Number(visitCount) + 1;
} else {
visitCount = 1;
}
// Store the updated count
sessionStorage.setItem('pageVisits', visitCount);
// Display the count for this session
sessionResultElement.innerHTML = `You have visited this page ${visitCount} time(s) in this session.`;
  • Synchronous: Both localStorage and sessionStorage operations are synchronous, meaning they can block the main browser thread if used excessively or with large amounts of data. Avoid complex operations on the main thread.
  • Storage Limits: While larger than cookies, there are still limits (typically 5-10MB). Don’t store huge amounts of data.
  • Security: Data is stored client-side and can be accessed via JavaScript, so don’t store sensitive information (like passwords or tokens) unless properly secured.
  • Alternatives: For larger, more complex data storage needs, or for asynchronous operations, consider using IndexedDB, a more powerful client-side database.