Skip to content

HTML5 - Web Storage

HTML5 Web Storage provides mechanisms for web applications to store data locally within the user’s browser. This allows applications to retain user preferences, offline data, and improve performance by caching assets.

Web Storage offers advantages over traditional cookies:

  • Larger Storage Capacity: Browsers typically allocate 5-10MB per origin for Web Storage, significantly more than the 4KB limit for cookies.
  • Not Sent with HTTP Requests: Stored data is not automatically sent with every HTTP request, reducing network overhead and improving security.
  • Client-Side Interface: Provides a simple synchronous JavaScript API for setting, retrieving, and removing data.

There are two main types of Web Storage: localStorage and sessionStorage.

Web Storage is supported by all modern browsers, including desktop and mobile versions.

sessionStorage maintains a separate storage area for each given origin that’s available for the duration of the page session (as long as the browser tab or window is open, including page reloads and restores).

Data stored in sessionStorage is specific to the window or tab it was created in. If the user opens the same web page in a new tab or window, it creates a new session with a separate storage area.

  • Storing temporary user input in multi-step forms.
  • Keeping track of user activity within a single session (e.g., items viewed).
  • Maintaining application state specific to a single browser tab.

The following code increments a counter each time the page is loaded within the same session:

<!DOCTYPE html>
<html>
<head>
<title>Session Storage Example</title>
</head>
<body>
<h1>Session Storage Page Counter</h1>
<p id="hitCount"></p>
<script>
// Check if sessionStorage is supported
if (typeof(Storage) !== "undefined") {
// Retrieve the current hit count from sessionStorage
let hits = sessionStorage.getItem('pageHits');
// If it doesn't exist, initialize it to 1, otherwise increment
if (hits) {
hits = Number(hits) + 1;
} else {
hits = 1;
}
// Store the updated count back into sessionStorage
sessionStorage.setItem('pageHits', hits);
// Display the count on the page
document.getElementById('hitCount').textContent = `Page loads this session: ${hits}`;
} else {
document.getElementById('hitCount').textContent = 'Sorry, your browser does not support Web Storage.';
}
</script>
<p>Refresh the page to increase the counter.</p>
<p>Close the tab/window and reopen the page to reset the counter.</p>
</body>
</html>

localStorage does the same thing as sessionStorage, but persists even when the browser is closed and reopened. The data remains available across sessions, tabs, and windows for the same origin until explicitly cleared by the user or the web application.

  • Storing user preferences (e.g., theme settings, language choice).
  • Keeping a user logged in across browser sessions (though more secure methods often involve server-side sessions).
  • Caching application data for offline use or faster startup.

This example saves and retrieves a user’s preferred theme:

<!DOCTYPE html>
<html>
<head>
<title>Local Storage Example</title>
<style id="themeStyle"></style>
</head>
<body>
<h1>Local Storage Theme Preference</h1>
<label for="themeSelect">Choose Theme:</label>
<select id="themeSelect">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<script>
const themeSelect = document.getElementById('themeSelect');
const themeStyle = document.getElementById('themeStyle');
function applyTheme(theme) {
if (theme === 'dark') {
themeStyle.textContent = 'body { background-color: #333; color: #eee; } select, label { color: #eee; }';
} else {
themeStyle.textContent = 'body { background-color: #fff; color: #333; } select, label { color: #333; }';
}
themeSelect.value = theme;
}
function saveThemePreference(theme) {
if (typeof(Storage) !== "undefined") {
localStorage.setItem('userTheme', theme);
} else {
console.warn('localStorage not supported, cannot save theme preference.');
}
}
// Load saved theme on page load
if (typeof(Storage) !== "undefined") {
const savedTheme = localStorage.getItem('userTheme') || 'light'; // Default to light
applyTheme(savedTheme);
} else {
console.warn('localStorage not supported, using default theme.');
applyTheme('light');
}
// Event listener for theme changes
themeSelect.addEventListener('change', (event) => {
const selectedTheme = event.target.value;
applyTheme(selectedTheme);
saveThemePreference(selectedTheme);
});
</script>
<p>Your theme preference will be saved even if you close the browser.</p>
</body>
</html>

Both localStorage and sessionStorage share the same API methods:

  • setItem(key, value): Adds or updates a key-value pair. Both key and value must be strings.
  • getItem(key): Retrieves the value associated with the key. Returns null if the key doesn’t exist.
  • removeItem(key): Removes the key-value pair associated with the key.
  • clear(): Removes all key-value pairs for that origin.
  • key(index): Returns the name of the key at the specified numerical index.
  • length: A read-only property returning the number of key-value pairs stored.

Important: Web Storage can only store strings. If you need to store objects or arrays, you must serialize them (e.g., using JSON.stringify()) before saving and deserialize them (using JSON.parse()) when retrieving.

// Storing an object
const userPrefs = { theme: 'dark', fontSize: 16 };
localStorage.setItem('preferences', JSON.stringify(userPrefs));
// Retrieving the object
const storedPrefsString = localStorage.getItem('preferences');
const retrievedPrefs = storedPrefsString ? JSON.parse(storedPrefsString) : {};
console.log(retrievedPrefs.theme); // Output: dark
  • Synchronous: The API operates synchronously, meaning calls can block the main browser thread if dealing with large amounts of data or slow disk access. For complex or large-scale storage, IndexedDB is preferred.
  • String Only: As mentioned, only strings can be stored directly.
  • Storage Limits: While larger than cookies, the 5-10MB limit can still be restrictive for some applications.
  • Security: Data is stored client-side and can be accessed or modified by any script running on the same origin. Do not store sensitive information (like passwords or tokens) in Web Storage.
  • No Querying: Web Storage is a simple key-value store. It lacks indexing or querying capabilities found in databases like IndexedDB.

For more advanced client-side storage needs requiring indexing, transactions, or larger data volumes, consider using the IndexedDB API.