Exploring localStorage, sessionStorage, and Cookies

Give your web applications a memory. Learn how to store data in the user's browser for better, more personalized experiences.

🧠

Welcome! Let's explore how websites remember information about you.

/* How does the web remember? */

localStorage: The Permanent Memory

localStorage is a web storage mechanism that saves data with no expiration date. The data will not be deleted when the browser is closed and will be available the next day, week, or year. It's perfect for storing user preferences like a theme (e.g., 'dark mode') or a username.

sessionStorage: The Temporary Notebook

sessionStorage is similar to localStorage but has a crucial difference: it only stores data for the duration of a page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Closing a tab or browser window will delete the data.

Cookies: The Server's Messenger

Cookies are small strings of data that a server sends to a user's browser. The browser stores them and sends them back with later requests to the same server. They're mainly used for session management (like logins), personalization, and tracking. They can have expiration dates and are sent with every HTTP request.

Which One Should I Use?

Choosing the right storage depends on your needs. Use localStorage for long-term user settings. Use sessionStorage for temporary data related to a single visit. Use Cookies when the server needs to know the data, such as for authentication.

Practice Zone


Interactive Test 1: Match the Concept

Match the storage type to its defining characteristic.

Arrastra en el orden correspondiente.


Arrastra las opciones:

localStorage
sessionStorage
Cookies

Completa el código:

Data persists forever______
Data is cleared on tab close______
Data is sent to the server______
Unlock with Premium

Interactive Test 2: Complete the Code

Complete the code to save a user's name so it remains even after they close the browser.

Rellena los huecos en cada casilla.

.setItem('username', 'Alex');
Unlock with Premium

Practice Example: Code Editor

Use the correct web storage to save a temporary 'sessionID'. It should not persist after the user closes the tab.

Enunciado:

* Escribe el código a continuación. Los caracteres correctos se mostrarán en verde y los incorrectos en rojo.

// Data will be gone after closing the tab sessionStorage.setItem('sessionID', 'xyz-123-abc');
Unlock with Premium

Knowledge Check

Which web storage method is most appropriate for storing a shopping cart's contents during a single browsing session?


Unlock with Premium

Practical Use Cases for Web Storage

Web storage isn't just theory. It's the engine behind many features you use daily. Let's see how it's done.


1. Saving User Preferences with `localStorage`

A "dark mode" toggle is a classic example. When a user picks a theme, you save it in `localStorage` so their choice is remembered the next time they visit.

const themeToggle = document.querySelector('#theme-btn');

// On click, save choice to localStorage
themeToggle.addEventListener('click', () => {
  document.body.classList.toggle('dark-mode');
  localStorage.setItem('theme', document.body.className);
});

// On page load, check for saved theme
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
  document.body.className = savedTheme;
}

2. Managing Multi-Step Forms with `sessionStorage`

If you have a long sign-up form, you can save the user's progress in `sessionStorage`. If they accidentally refresh the page, their data isn't lost. Since it's sensitive info, you don't want it stored forever.

const form = document.querySelector('#signup-form');

// Save input values on every change
form.addEventListener('input', (e) => {
  sessionStorage.setItem(e.target.name, e.target.value);
});

// On page load, populate form from sessionStorage
for (let i = 0; i < sessionStorage.length; i++) {
  const key = sessionStorage.key(i);
  const input = form.querySelector(`[name="${key}"]`);
  if (input) input.value = sessionStorage.getItem(key);
}

3. Handling Authentication with Cookies

When you log into a site, the server sends back a cookie containing a unique session ID. Your browser automatically includes this cookie in all future requests, proving to the server that you're logged in. JavaScript usually doesn't need to manage this directly.

// Server Response Header after successful login
Set-Cookie: sessionId=a3fWa; HttpOnly; Secure; SameSite=Strict

// Browser automatically sends this on next request
Cookie: sessionId=a3fWa

Practical Takeaway: Use `localStorage` for user settings, `sessionStorage` for temporary session data, and rely on `cookies` (often managed by the server) for authentication.

Web Storage Glossary

localStorage
A storage mechanism that saves key-value pairs persistently in the browser. Data survives browser restarts.
sessionStorage
A storage mechanism that saves key-value pairs for a single browser session. Data is cleared when the tab is closed.
Cookies
Small pieces of data stored by the browser that are sent back to the server with each request. Can have expiration dates.
setItem(key, value)
Method used to add or update a key-value pair in `localStorage` or `sessionStorage`.
getItem(key)
Method used to retrieve the value associated with a key from `localStorage` or `sessionStorage`.
removeItem(key)
Method to delete a specific key-value pair from storage.
clear()
Method to remove all key-value pairs from storage.
Capacity
`localStorage` and `sessionStorage` can typically store much more data (5-10MB) than cookies (around 4KB).