A four-step form, a search filter, a reading position: all of them matter for the length of a visit and become a nuisance the next day.
For that case the browser offers a space with the same interface as permanent storage, but a very different life expectancy.
Definition
sessionStorage is a key-value store attached to an origin and to a tab. Data survives reloads and navigation inside the site, and disappears when the tab is closed.
sessionStorage.setItem("step", "3");
sessionStorage.setItem("draft", JSON.stringify({ name: "Camille" }));
console.log(sessionStorage.getItem("step")); // "3"
console.log(sessionStorage.length); // 2
sessionStorage.removeItem("draft");The methods are exactly those of localStorage: setItem, getItem, removeItem, clear, plus length and key. Values are strings here too, so an object goes through JSON.
What keeps it and what clears it
The lifetime does not follow intuition. The table sums it up across two columns: the visitor's action, and what is left afterward.
| Action | State of the store |
|---|---|
| Page reload | Kept |
| Navigation inside the same site | Kept |
| Browser back button | Kept |
| Duplicating the tab | Copied into the new tab |
| New tab opened by hand | Empty |
| Closing the tab | Erased |
The fourth row often surprises people: duplicating a tab does not share the store, it makes an independent copy that will then drift on its own.
The typical use case
Saving progress through a long form protects against an accidental reload, without leaving a trace once the visit is over.
const field = document.querySelector("#address");
field.value = sessionStorage.getItem("address") ?? "";
field.addEventListener("input", () => {
sessionStorage.setItem("address", field.value);
});The Nullish coalescing (??) operator avoids writing the string "null" into the field on the first pass, when the key does not exist yet.
This store has nothing to do with a server session. It never travels inside a request, no authentication data passes through it, and the server cannot see it.
Frequently asked questions
Do two tabs of the same site share their data?
No, and that is the essential difference with permanent storage. Each tab owns its own store, even on identical pages. To share information between tabs you have to go through localStorage or a dedicated broadcast channel.
Is there an event when a value changes?
The storage event does exist, but it only fires in other documents of the same origin. Since this store is not shared between tabs, it is almost never useful here. Inside a single tab, calling the relevant function yourself right after the write is the better move.
How much can I store in it?
The order of magnitude matches permanent storage, a few megabytes per origin, with variation between browsers. Going over throws a quota error, which interrupts the function if nobody catches it. A try block around the write remains the minimum precaution.