This post looks at ways to store data on the client, in the user's browser. Cookies were once the main option, but their limited capacity and automatic inclusion in HTTP requests can add network overhead. HTML5 introduced the
Web Storage API
, whose two main interfaces are
local storage
and
session storage
.
The two are easy to confuse because their APIs are nearly identical. The key difference is how long the data survives. Let's compare their behavior and see when to use each.
Local Storage Persists Across Browser Restarts ๐
Local storage
is a key-value store that keeps data in the user's browser
persistently
. The data survives closing the browser window or restarting the computer. It has no automatic expiration and can be deleted explicitly with JavaScript.
Store settings that should persist when users close and reopen the browser, such as a remembered username for sign-in or a preference for dark or light mode.
Session Storage Lasts for the Life of the Tab ๐
Session storage
is also a key-value store, but its data lasts
only for the current session
. Think of a session here as belonging to
one browser tab
. When the user closes the tab, its session storage data disappears.
Usage
The API methods are the same as those for local storage.
Keep information needed temporarily in one tab. You could save an in-progress form so a refresh does not erase it, remember the current page's scroll position, or store whether the user dismissed a one-time pop-up or notice with a โDon't show again todayโ option.
The central distinction is how the data reaches the server.
The biggest differences are
server communication
and
capacity
.
The browser automatically includes applicable
cookies
in HTTP request headers, so they can maintain state the server needs, such as authentication. This adds to network traffic, and a cookie is small, typically around 4 KB.
Web storage
stays on the client and is never sent to the server automatically. JavaScript has to retrieve and send the data explicitly. With a capacity of roughly 5โ10 MB, it is better suited to data used only on the client.