JavaScript: sessionStorage (In-Depth)
sessionStorage is part of the Web Storage API. Like localStorage, it stores key-value pairs, but only for the duration of the page session. When the browser tab or window is closed, the data is cleared.
Basic Usage
sessionStorage.setItem("score", "200");
let score = sessionStorage.getItem("score"); // "200"
sessionStorage.removeItem("score");
sessionStorage.clear(); // Removes all keys for this session
Differences from localStorage
- sessionStorage is cleared when the page session ends (tab/window closed).
- Data is NOT shared between tabs/windows.
- Otherwise, API and storage limits are similar.
Data is Stored as Strings
sessionStorage.setItem("user", JSON.stringify({ name: "Bob" }));
let userObj = JSON.parse(sessionStorage.getItem("user"));
When to Use sessionStorage
- Temporary data (like wizard progress, tab state, etc.)
- One-time tokens needed for the current tab only
- Data that should not persist after the window is closed
Practice: Try opening two tabs and see how sessionStorage is unique to each. Close a tab and see the data vanish!