📄

Web Storage API

Advanced
110 XP
40 min
Lesson Content

Web Storage API

The Web Storage API allows you to store data in the user's browser. It's more powerful than cookies and provides two storage mechanisms: localStorage and sessionStorage.

localStorage

Stores data with no expiration date. Data persists even after the browser is closed.

// Store data
localStorage.setItem('username', 'John');
localStorage.setItem('theme', 'dark');

// Retrieve data
const username = localStorage.getItem('username');

// Remove data
localStorage.removeItem('username');

// Clear all data
localStorage.clear();

sessionStorage

Stores data for one session. Data is cleared when the browser tab is closed.

// Store data
sessionStorage.setItem('tempData', 'value');

// Retrieve data
const data = sessionStorage.getItem('tempData');

// Remove data
sessionStorage.removeItem('tempData');

Storing Objects

Web Storage only stores strings. To store objects, use JSON:

// Storing an object
const user = { name: 'John', age: 30 };
localStorage.setItem('user', JSON.stringify(user));

// Retrieving an object
const storedUser = JSON.parse(localStorage.getItem('user'));

Storage Events

Listen for storage changes (useful for multi-tab communication):

window.addEventListener('storage', (e) => {
console.log('Key:', e.key);
console.log('Old value:', e.oldValue);
console.log('New value:', e.newValue);
});

Storage Limits

  • Most browsers allow 5-10MB per origin
  • localStorage: Persistent across sessions
  • sessionStorage: Cleared when tab closes
  • Both are domain-specific (same-origin policy)

Use Cases

  • User preferences (theme, language)
  • Shopping cart data
  • Form data auto-save
  • Game progress
  • Offline data caching

Best Practices

  • Always use try-catch when accessing storage (may be disabled)
  • Don't store sensitive information (passwords, credit cards)
  • Check if storage is available before using
  • Use JSON.stringify/parse for complex data
  • Clear old data periodically

Checking Storage Availability

function storageAvailable(type) {
try {
const storage = window[type];
const x = '__storage_test__'; storage.setItem(x, x); storage.removeItem(x); return true; } catch (e) { return false; } }

if (storageAvailable('localStorage')) {
// Use localStorage
}
Example Code

Create a page that saves and retrieves user preferences using localStorage.

<!DOCTYPE html>
<html>
  <head>
    <title>Web Storage Demo</title>
  </head>
  <body>
    <h1>Settings</h1>
    <input type="text" id="username" placeholder="Enter username">
    <button onclick="saveData()">Save</button>
    <button onclick="loadData()">Load</button>
    <button onclick="clearData()">Clear</button>
    <p id="display"></p>
    
    <script>
      function saveData() {
        // Get username from input
        // Save to localStorage
        // Show confirmation message
      }
      
      function loadData() {
        // Get data from localStorage
        // Display in #display paragraph
      }
      
      function clearData() {
        // Clear localStorage
        // Clear the display
      }
    </script>
  </body>
</html>

Expected Output:

A working storage demo
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code