Skip to main content

JavaScript DOM Storage

Introduction

When building web applications, you often need a way to store user data on the client side. Whether it's remembering user preferences, saving form data, or maintaining application state between page refreshes, JavaScript DOM Storage provides powerful tools to persist data directly in the browser.

In this tutorial, we'll explore the three main client-side storage mechanisms:

  1. localStorage - Stores data with no expiration date
  2. sessionStorage - Stores data for one session
  3. Cookies - Small text files stored in the browser with customizable expiration

These storage options allow you to create more responsive applications that retain information without always needing to communicate with the server.

Local Storage

localStorage is a type of web storage that allows you to store key-value pairs in the browser with no expiration date. The data will persist even after the browser is closed and reopened.

Basic localStorage Operations

Storing Data

javascript
// Storing a simple string
localStorage.setItem('username', 'JohnDoe');

// Storing a number (values are always stored as strings)
localStorage.setItem('userScore', 100);

// Storing an object (must be converted to JSON string)
const userPreferences = {
theme: 'dark',
fontSize: 'medium',
notifications: true
};
localStorage.setItem('preferences', JSON.stringify(userPreferences));

Retrieving Data

javascript
// Getting a simple string
const username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe

// Getting a number (needs to be parsed)
const score = Number(localStorage.getItem('userScore'));
console.log(score); // Output: 100

// Getting an object (needs to be parsed from JSON)
const preferences = JSON.parse(localStorage.getItem('preferences'));
console.log(preferences.theme); // Output: dark

Removing Data

javascript
// Remove a specific item
localStorage.removeItem('username');

// Clear all localStorage data
localStorage.clear();

localStorage Limitations

  • Storage limit is typically around 5-10MB (varies by browser)
  • Can only store strings (objects must be serialized)
  • Operations are synchronous and block the main thread
  • Storage is per domain (not shared between different origins)

Session Storage

sessionStorage works exactly like localStorage but with one key difference: the data is cleared when the page session ends (when the tab or browser is closed).

Basic sessionStorage Operations

javascript
// Store data
sessionStorage.setItem('currentPage', 'dashboard');

// Retrieve data
const currentPage = sessionStorage.setItem('currentPage');
console.log(currentPage); // Output: dashboard

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

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

When to Use sessionStorage

Use sessionStorage when you need to store temporary data that shouldn't persist after the user closes the browser, such as:

  • Form data during multi-step processes
  • Temporary user preferences
  • Current application state within a session

Cookies

Cookies are the original browser storage mechanism and differ from localStorage and sessionStorage in several ways. They're automatically sent to the server with HTTP requests, can have an expiration date, and have size limitations.

javascript
// Set a simple cookie that expires in 7 days
document.cookie = "username=JohnDoe; expires=" + new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toUTCString();

// Set a cookie with more options
document.cookie = "userTheme=dark; expires=" + new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toUTCString() + "; path=/; secure; samesite=strict";

Reading Cookies

javascript
// Read all cookies
const allCookies = document.cookie;
console.log(allCookies); // Output: "username=JohnDoe; userTheme=dark"

// Function to get a specific cookie
function getCookie(name) {
const cookieArr = document.cookie.split(';');
for(let i = 0; i < cookieArr.length; i++) {
const cookiePair = cookieArr[i].split('=');
if(name === cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}

const theme = getCookie('userTheme');
console.log(theme); // Output: dark
javascript
// Set the cookie's expiration to a past date
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
  • expires/max-age: Sets when the cookie will expire
  • path: Specifies the URL path where the cookie is valid
  • domain: Specifies which domain the cookie is valid for
  • secure: Cookie will only be sent over HTTPS
  • samesite: Controls when cookies are sent with requests from external sites
  • httpOnly: Makes the cookie inaccessible to JavaScript (can only be set by the server)

Storage Events

When using localStorage (but not sessionStorage), you can listen for changes made from other tabs or windows using the storage event:

javascript
// Listen for changes to localStorage
window.addEventListener('storage', (event) => {
console.log('Storage changed!');
console.log('Key:', event.key);
console.log('Old value:', event.oldValue);
console.log('New value:', event.newValue);
console.log('URL of document that changed the storage:', event.url);
});

This event fires only in other windows/tabs when the localStorage is changed, not in the window that made the change.

Real-World Applications

Let's explore some practical examples of how to use these storage mechanisms in real applications:

Example 1: Theme Switcher

javascript
// HTML
// <button id="themeToggle">Toggle Theme</button>

// JavaScript
document.addEventListener('DOMContentLoaded', () => {
// Check if user has a saved theme preference
const currentTheme = localStorage.getItem('theme') || 'light';
document.body.classList.add(currentTheme);

// Listen for theme toggle button clicks
document.getElementById('themeToggle').addEventListener('click', () => {
// Toggle the theme
if (document.body.classList.contains('light')) {
document.body.classList.replace('light', 'dark');
localStorage.setItem('theme', 'dark');
} else {
document.body.classList.replace('dark', 'light');
localStorage.setItem('theme', 'light');
}
});
});

Example 2: Shopping Cart Using sessionStorage

javascript
// Function to add an item to cart
function addToCart(product) {
// Get existing cart or initialize empty array
let cart = JSON.parse(sessionStorage.getItem('cart')) || [];

// Add new product to cart
cart.push(product);

// Save updated cart
sessionStorage.setItem('cart', JSON.stringify(cart));

// Update cart UI
updateCartUI();
}

// Function to update cart UI
function updateCartUI() {
const cartElement = document.getElementById('cart');
const cart = JSON.parse(sessionStorage.getItem('cart')) || [];

// Clear previous items
cartElement.innerHTML = '';

// Show cart items or empty message
if (cart.length === 0) {
cartElement.innerHTML = '<p>Your cart is empty</p>';
return;
}

// Create list of items
const ul = document.createElement('ul');
cart.forEach(item => {
const li = document.createElement('li');
li.textContent = `${item.name} - $${item.price}`;
ul.appendChild(li);
});

cartElement.appendChild(ul);

// Add total
const total = cart.reduce((sum, item) => sum + item.price, 0);
const totalElement = document.createElement('p');
totalElement.textContent = `Total: $${total}`;
cartElement.appendChild(totalElement);
}

// Initialize cart on page load
document.addEventListener('DOMContentLoaded', updateCartUI);

Example 3: Remember Me Login with Cookies

javascript
// Handle login form submission
document.getElementById('loginForm').addEventListener('submit', function(e) {
e.preventDefault();

const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const rememberMe = document.getElementById('rememberMe').checked;

// Authenticate user (in a real app, this would involve server validation)
if (authenticateUser(username, password)) {
if (rememberMe) {
// Set cookie to expire in 30 days
const expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 30);
document.cookie = `rememberedUser=${username}; expires=${expiryDate.toUTCString()}; path=/; samesite=strict`;
}

// Redirect to dashboard
window.location.href = '/dashboard';
} else {
alert('Invalid username or password');
}
});

// Check for remembered user on page load
document.addEventListener('DOMContentLoaded', function() {
const rememberedUser = getCookie('rememberedUser');
if (rememberedUser) {
document.getElementById('username').value = rememberedUser;
document.getElementById('rememberMe').checked = true;
}
});

// Helper function to get cookie value
function getCookie(name) {
const cookieArr = document.cookie.split(';');
for(let i = 0; i < cookieArr.length; i++) {
const cookiePair = cookieArr[i].split('=');
if(name === cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}

Choosing the Right Storage Option

Here's a quick comparison to help you choose the right storage option:

FeaturelocalStoragesessionStorageCookies
Capacity~5-10MB~5-10MB~4KB
ExpirationNeverTab closeConfigurable
Sent with requestsNoNoYes
AccessibilityAny windowSame tabAny window
APISimpleSimpleComplex
Use CaseLong-term preferencesTemporary session dataAuthentication

Security Considerations

When working with client-side storage, keep these security considerations in mind:

  1. Never store sensitive information (passwords, tokens, personal data) in any client-side storage without proper encryption
  2. Be aware of XSS vulnerabilities that can expose stored data
  3. For authentication, use HttpOnly and Secure flags on cookies
  4. Remember that users can view and modify all client-side storage
  5. Set appropriate SameSite cookie attributes to prevent CSRF attacks

Summary

JavaScript DOM Storage provides several ways to store data in the browser:

  • localStorage is perfect for persistent data that should be available across browser sessions.
  • sessionStorage is ideal for temporary data that should only persist during the current browser session.
  • Cookies are best for data that needs to be sent to the server with each request, or when you need fine-grained control over expiration.

By understanding when and how to use each storage option, you can build more responsive and user-friendly web applications that maintain state and provide a smoother experience for your users.

Exercises

  1. Create a simple note-taking app that saves notes to localStorage.
  2. Build a multi-step form that uses sessionStorage to remember form field values between steps.
  3. Implement a cookie consent banner that remembers when a user has accepted cookies.
  4. Create a product browsing history feature that shows the last 5 products a user viewed.
  5. Build a theme switcher that uses localStorage to remember the user's preferred theme.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)