JavaScript Web Storage

Give your web applications a memory. Master localStorage, sessionStorage, and Cookies to store data and create persistent, user-friendly experiences.

Lesson ProgressStep 1 of 7
0 EXP

Welcome! Let's learn how websites remember you. This is client-side storage.

// The web's memory...

What is Client-Side Storage?

HTTP is **stateless**, which means a web server treats every request as a new, isolated event. To create personalized experiences (like remembering a login, theme preference, or shopping cart), we must store data in the user's browser. This is **client-side storage**.

The three main ways to store data are:

  • `localStorage`: A permanent vault for data.
  • `sessionStorage`: A temporary notebook for a single session.
  • `Cookies`: Small pieces of data sent to and from the server.

System Check

Which of these is NOT a client-side storage mechanism?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

🏆
Data Setter

Successfully store your first piece of data in localStorage.

🏗️
Storage Strategist

Correctly identify the use case for each storage type.

✍️
Security Expert

Master the security concepts of web storage.

Mission: Save User Preferences

Your user wants to save their username. Use `localStorage` to save the key `'username'` with the value `'CyberRunner'`.

A.D.A. Feedback:

> Awaiting input...

Challenge: Match the Property

Drag the descriptions on the left to match the storage type on the right.

Lasts for one session/tab
Lasts forever (persistent)
Sent to server with every request
localStorage
sessionStorage
Cookies

Challenge: Complete the Syntax

Fill in the missing parts of the code to use the storage APIs.

window..setItem('temp', 'data');
const data = localStorage.('theme');
document. = 'user=123';

Consult A.D.A.

Community Holo-Net

Peer Project Review

Submit your "User Preference Saver" project for feedback from other Net-Runners.

Beyond the Request: A Deep Dive into Client-Side Storage

The web, by its original design, has amnesia. The HTTP protocol is **stateless**, meaning each request from a user to a server is treated as a completely independent event. The server doesn't inherently remember you from one click to the next. To build modern, interactive applications that feel personal—like remembering a login, a theme preference, or a shopping cart—we need a way to store data on the user's device. This is where **client-side storage** comes in.

The Web Storage API: `localStorage` and `sessionStorage`

Modern browsers provide a `Window.Storage` API, which gives us two powerful, easy-to-use mechanisms: `localStorage` and `sessionStorage`. Both store data as **key-value pairs** and, crucially, **they only store strings**. To store objects or arrays, you must first serialize them with JSON.stringify() and deserialize them with JSON.parse().

1. `localStorage`: The Digital Vault

`localStorage` is for **persistent** data. Data stored here has **no expiration date**. It will remain on the user's computer until it is explicitly cleared by the user (by clearing their browser cache) or by your web application. It's available across all tabs and windows of the same origin.

  • **Capacity:** Around 5-10MB (browser-dependent).
  • **Persistence:** Permanent, until manually cleared.
  • **Scope:** All tabs/windows from the same origin.
  • **Use Cases:** User preferences (like 'dark-mode'), remembering a user's name, or other non-sensitive data you want to persist between visits.
// Store an object
const userPrefs = { theme: 'dark', notifications: false };
localStorage.setItem('preferences', JSON.stringify(userPrefs));

// Retrieve and parse the object
const savedPrefs = JSON.parse(localStorage.getItem('preferences'));
console.log(savedPrefs.theme); // "dark"

// Remove the item
localStorage.removeItem('preferences');

// Clear all items for this origin
localStorage.clear();

2. `sessionStorage`: The Temporary Scratchpad

`sessionStorage` is for **session-only** data. It has the exact same API as `localStorage` (`setItem`, `getItem`, etc.), but with one critical difference: its data is cleared the moment the **page session ends**. A page session lasts as long as the browser tab is open. When the user closes the tab, the data is gone.

  • **Capacity:** Around 5-10MB (browser-dependent).
  • **Persistence:** For the lifetime of the tab.
  • **Scope:** Only the tab that created it.
  • **Use Cases:** Storing data for a multi-step form (so the user doesn't lose progress on refresh), temporary application state, or items in a shopping cart before checkout.

`Cookies`: The Server's Messenger

Cookies are the "old guard" of client-side storage. They are tiny bits of data (max ~4KB) that a server sends to the browser, which the browser then stores. The key difference is that cookies are **sent back to the server with every subsequent HTTP request** to that same domain. This is what makes them ideal for authentication, but also their biggest drawback (it adds overhead).

While you can set cookies with JavaScript (`document.cookie = "..."`), they are often set by the server via an HTTP header. They have powerful attributes:

  • `HttpOnly`: **The most important security attribute.** When set, the cookie is inaccessible to client-side JavaScript (`document.cookie` won't see it). This makes it **immune to XSS attacks** where a hacker tries to steal the cookie.
  • `Secure`: Ensures the cookie is only sent over HTTPS, preventing it from being intercepted on insecure (HTTP) connections.
  • `SameSite` (`Strict`, `Lax`, `None`): A powerful defense against **CSRF (Cross-Site Request Forgery)** attacks. It controls whether a cookie is sent with requests initiated from other domains.
  • `Max-Age` / `Expires`: Sets the cookie's expiration date. If omitted, it becomes a "session cookie" and is cleared when the browser closes.

The Great Debate: `localStorage` vs. `HttpOnly` Cookies for Auth

A common task is storing an authentication token (like a JWT) after a user logs in. Where should it go?

❌ Storing JWT in `localStorage`

**Vulnerable to XSS (Cross-Site Scripting).** If a hacker can inject any JavaScript onto your site, they can simply read localStorage.getItem('token') and steal the user's session.

✔️ Storing JWT in `HttpOnly` Cookie

**Secure against XSS.** Since JavaScript can't read the cookie, the hacker gets nothing. The browser handles sending the auth token securely with each request. This is the modern, recommended practice.

Key Takeaway: Use `localStorage` for non-sensitive user preferences. Use `sessionStorage` for temporary, in-tab data. Use **`HttpOnly`, `Secure`, `SameSite` cookies** for all sensitive data, especially authentication tokens.

Web Storage & Security Glossary

Stateless (HTTP)
A design principle where a protocol (like HTTP) does not retain any information about previous requests. Each request is treated as new.
`localStorage`
A Web Storage API object for storing key-value pairs persistently (with no expiration) in the browser. Scope is by origin.
`sessionStorage`
A Web Storage API object for storing key-value pairs for the duration of a single page session (i.e., until the tab is closed).
Cookies
Small pieces of data (max 4KB) stored by the browser and sent to the server with every HTTP request. Used for authentication and tracking.
`JSON.stringify()`
A JavaScript method to convert a JavaScript object or array into a JSON string. Necessary for storing objects in Web Storage.
`HttpOnly` (Cookie Attribute)
A security attribute for cookies that prevents client-side JavaScript from accessing it. This is the primary defense against XSS-based
`Secure` (Cookie Attribute)
A security attribute that ensures a cookie is only transmitted over HTTPS.
`SameSite` (Cookie Attribute)
A security attribute that helps prevent CSRF attacks by controlling whether a cookie is sent with cross-origin requests. Values: `Strict`, `Lax`, `None`.
XSS (Cross-Site Scripting)
A security vulnerability where an attacker injects malicious client-side scripts into a webpage. This script can steal data from `localStorage` or non-`HttpOnly` cookies.
CSRF (Cross-Site Request Forgery)
A security vulnerability where an attacker tricks a logged-in user into unknowingly executing an action on a website (e.g., changing their password). `SameSite` cookies are the primary defense.
IndexedDB
A more complex, low-level browser API for storing large amounts of structured data, including files. It's an asynchronous database.

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of senior JavaScript developers and security experts, focusing on modern best practices for client-side data handling.

Verification and Updates

Last reviewed: October 2025.

Content is verified against the latest ECMAScript and browser security standards. We prioritize security recommendations from OWASP (Open Web Application Security Project).

External Resources

Found an error or have a suggestion? Contact us!