Conceptly
← All Concepts
πŸ’Ύ

Web Storage API

State ManagementA client-side API for storing key-value data in the browser

The Web Storage API is a client-side store that allows key-value data to be stored in the browser. localStorage persists data even after the browser is closed, while sessionStorage is cleared when the tab is closed. Unlike cookies, data is not automatically transmitted to the server, and the generous capacity of 5 to 10 MB per domain makes it well suited for storing data that is only used on the client side. Data can be read and written synchronously using simple APIs such as setItem, getItem, and removeItem.

β–ΆArchitecture Diagram

πŸ” Structure

Dashed line animations indicate the flow direction of data or requests

Why do you need it?

There are many situations where cookies alone cannot satisfy the need to store data in the browser. Because cookies are automatically sent to the server on every HTTP request, putting data that the server has no need to see into a cookie generates unnecessary traffic on every request. The limit of around 4 KB per cookie and only a few dozen cookies per domain means that even modest amounts of data quickly run out of space. When a user turns on dark mode, collapses a sidebar, or changes the sort order of a list, those are settings that only matter inside the browser. Sending that data to the server is overkill, and discarding it on every reload hurts the user experience. There was a need for a way to store data that stays in the browser, offers more space than cookies, and carries no server transmission overhead.

Why did this approach emerge?

As the web evolved from a simple document viewer into an application platform, the amount of state that had to be maintained on the client side kept growing. Cookies were originally designed for exchanging state with the server, so they were inadequate for client-only data -- both in terms of capacity and the burden of being transmitted with every request. When the HTML5 specification included the Web Storage API in 2009, browsers gained for the first time an independent key-value store that was separate from HTTP. Around the same time, as web applications grew in complexity and the SPA (Single Page Application) pattern spread, the demand for maintaining client-side state without full page transitions drove rapid adoption of Web Storage.

How does it work inside?

The Web Storage API is divided into two stores, both sharing the same interface. localStorage stores data permanently. It survives closing and reopening the browser and restarting the computer, and it will not disappear unless the developer calls removeItem or clear, or the user manually clears their browser data. Tabs sharing the same domain share the same localStorage. sessionStorage is tied to the lifetime of a browser tab. Opening the same site in a new tab gives each tab its own independent sessionStorage, and closing the tab deletes that store. It is well suited for temporarily holding data being entered into a form or managing state that is only valid during a single visit. Both stores operate on string key-value pairs. To store an object or array, it must first be converted with JSON.stringify, and retrieved with JSON.parse. The API executes synchronously, so reading or writing large amounts of data at once can momentarily block the main thread. This warrants attention in performance-sensitive situations. From a security standpoint, Web Storage follows the same-origin policy, meaning only pages from the same origin (protocol + domain + port) can access it. However, because JavaScript can access it freely, any XSS vulnerability will expose the stored data to an attacker. Storing authentication tokens or sensitive information in Web Storage is not recommended.

In Code

Persisting state to localStorage after each change

import { useEffect, useState } from "react";

export function ThemeToggle() {
  const [theme, setTheme] = useState("light");

  useEffect(() => {
    localStorage.setItem("theme", theme);
  }, [theme]);

  return <button onClick={() => setTheme("dark")}>Change theme</button>;
}

The state change is mirrored into localStorage, so you can read how the value survives a refresh.

localStorage and sessionStorage share an API but not a lifetime

localStorage.setItem("sidebar", "collapsed");
sessionStorage.setItem("draft", "meeting notes");

const savedDraft = sessionStorage.getItem("draft");

The same `setItem` call behaves differently because one store survives longer and the other is tied to the current tab.

What is it often confused with?

Web Storage and cookies both store data in the browser, but their design purposes differ. Cookies are automatically transmitted to the server and used for the server to identify users; Web Storage retains data exclusively on the client, independently of the server. The capacity difference is also significant -- 4 KB for cookies versus 5 to 10 MB for Web Storage. Web Storage and IndexedDB are also often compared. Web Storage stores only string key-value pairs via a synchronous API and is suited for simple configuration values. IndexedDB is a client-side database that handles structured data asynchronously and supports indexed lookups. For simple values of up to a few dozen kilobytes, Web Storage is the convenient choice; for larger data volumes or when search is required, IndexedDB is appropriate. The criterion for choosing between localStorage and sessionStorage is the lifetime of the data. If it should still be there when the user returns later, use localStorage. If it should disappear when the tab is closed, use sessionStorage.

When should you use it?

Web Storage is widely used as the simplest way to persist client-side state in SPAs. Storing user preferences such as selected theme, language, and sort order in localStorage means the same environment can be restored on refresh or return visits. On pages with long forms, a common pattern is to periodically save input data to sessionStorage so that accidentally refreshing the tab does not lose the content being written. Because the data disappears naturally when the tab is closed, no separate cleanup code is needed. One practice to be cautious about is storing authentication tokens in Web Storage. Because localStorage is freely accessible by JavaScript, any XSS vulnerability will allow the stored token to be stolen outright. It is safer to keep authentication-related data in HttpOnly cookies. Web Storage is the right choice for data whose exposure would not lead to a security incident. Another detail that is easy to miss in production is that in private browsing (incognito) mode, the behavior of localStorage can differ by browser or its capacity may be restricted. Features that depend on Web Storage should include fallback code for the case where storage fails.

UI state persistence -- sidebar open/closed state, theme settings, language selection, and similar preferencesForm draft saving -- preserving content being entered until the tab is closedOffline cache -- storing API responses for display without a network connectionUser defaults -- remembering sort order, filter conditions, and the last viewed item