SessionStorage

A web storage API similar to LocalStorage, but data is cleared when the browser tab is closed, providing temporary storage for the duration of a page session.

Overview

SessionStorage provides the same API as LocalStorage but with one key difference: the data is only available for the duration of the page session. It's cleared when the tab is closed. Each tab has its own separate SessionStorage, making it perfect for storing temporary data that shouldn't persist across sessions.

Example

javascript
// Store data (same API as localStorage)
sessionStorage.setItem('currentStep', '3');
sessionStorage.setItem('formData', JSON.stringify({ name: 'Alice' }));

// Retrieve data
const step = sessionStorage.getItem('currentStep');
console.log(step); // '3'

// Remove item
sessionStorage.removeItem('currentStep');

// Clear all session data
sessionStorage.clear();

// Practical use case: multi-step form
function saveFormStep(stepNumber, data) {
  sessionStorage.setItem('formStep', stepNumber);
  sessionStorage.setItem(`formData${stepNumber}`, JSON.stringify(data));
}

function loadFormStep() {
  const step = sessionStorage.getItem('formStep');
  if (step) {
    const data = JSON.parse(sessionStorage.getItem(`formData${step}`));
    return { step, data };
  }
  return null;
}

Key Points

  • Cleared when tab is closed
  • Separate storage per tab
  • Same API as LocalStorage
  • 5-10MB storage limit
  • Perfect for temporary session data

Learn More