JavaScript Session Storage
Table of Contents + β
In the previous lesson, we learned how to save data in the browser with localStorage. Now letβs look at sessionStorage, which works the same way but keeps data only for the current tab session.
π¦ What is Session Storage?
sessionStorage stores key-value pairs in the browser, exactly like localStorage. It uses the same methods, so everything you already know carries over. The one big difference is how long the data lives: sessionStorage is cleared the moment the tab is closed.
It also has its own object, available on window.sessionStorage or simply sessionStorage.
sessionStorage.setItem("step", "2"); // save a valueconst step = sessionStorage.getItem("step"); // read it backconsole.log(step); // "2"
sessionStorage.removeItem("step"); // delete one keysessionStorage.clear(); // delete everythingLetβs walk through what each line does:
setItem("step", "2")saves the value"2"under the key"step".getItem("step")reads that value back and stores it instep, which logs"2".removeItem("step")deletes just the"step"key.clear()wipes every key in this tabβssessionStorage.
The method names match localStorage one for one. If you can use one, you can use the other.
π The Key Difference from localStorage
Both APIs are identical to write code against. What changes is the lifetime of the data and who can see it. The table below shows the difference.
| Feature | localStorage | sessionStorage |
| Lifetime | Persists until you delete it | Cleared when the tab is closed |
| Scope | Shared across all tabs of the site | Separate for each tab |
| Survives reload | Yes | Yes |
| API | setItem, getItem, removeItem, clear | setItem, getItem, removeItem, clear |
Per tab means per tab
Open the same page in two tabs and each gets its own sessionStorage. A value
saved in one tab is invisible to the other.
πΎ A Simple Example
Use sessionStorage when you only need a value for as long as the tab is open. Here we store a temporary value for the current session.
// β
Save a value for this tab sessionsessionStorage.setItem("username", "Alex");
// Read it back later, even after a page reloadconst username = sessionStorage.getItem("username");console.log(username); // "Alex"Here is what each step does:
setItem("username", "Alex")saves the name"Alex"under the key"username"for this tab.getItem("username")reads that name back into theusernamevariable, which logs"Alex".
The value stays available while the tab is open and across reloads. Close the tab, and it is gone.
π§± Storing Objects with JSON
sessionStorage can only hold strings, just like localStorage. To store an object or array, turn it into a string with JSON.stringify when saving and back into an object with JSON.parse when reading.
const filters = { category: "books", inStock: true };
// β
Convert the object to a string before savingsessionStorage.setItem("filters", JSON.stringify(filters));
// β
Parse the string back into an object when readingconst saved = JSON.parse(sessionStorage.getItem("filters"));console.log(saved.category); // "books"Letβs trace the round trip:
- We start with a
filtersobject holding a category and an in-stock flag. JSON.stringify(filters)turns that object into a string, whichsetItemthen saves under"filters".getItem("filters")reads the string back, andJSON.parserebuilds it into a real object stored insaved.saved.categoryreads a property off that rebuilt object, logging"books".
The next block shows what happens when you skip the JSON.stringify step and save the object directly.
// β Saving an object directly stores the text "[object Object]"sessionStorage.setItem("filters", filters);Because setItem only stores strings, it calls toString() on the object first, which turns it into the useless text "[object Object]" instead of your real data.
π A Practical Example
A common use is remembering a choice only for the current tab, such as a form step or a list filter. The user keeps their place on reload, but a fresh tab starts clean.
// Remember which step of a multi-step form the user is onfunction saveStep(step) { sessionStorage.setItem("formStep", step);}
function loadStep() { // Default to step 1 if nothing is saved yet return Number(sessionStorage.getItem("formStep")) || 1;}
saveStep(3);console.log(loadStep()); // 3Here is how this code works:
saveSteptakes a step number and saves it under the key"formStep".loadStepreads that value back, wraps it inNumber(...)to turn the stored string into a number, and falls back to1with|| 1when nothing is saved yet.- Calling
saveStep(3)thenloadStep()stores step 3 and reads it back, logging3.
Because this lives in sessionStorage, opening the form in a new tab starts at step 1 again, which is usually what you want for a one-time flow.
Pick the right tool
Use sessionStorage for short-lived, per-tab data like a draft or a filter.
Use localStorage for data that should stick around, like a theme choice.
β οΈ Common Mistakes to Avoid
| Mistake | Problem | Solution |
| Expecting data to last after closing the tab | The data is wiped when the tab closes | Use localStorage for data that must persist |
Confusing it with localStorage | Data set in one is not found in the other | Read and write with the same storage object |
| Storing an object without JSON | You get "[object Object]" back | Use JSON.stringify to save and JSON.parse to read |
π§ Try It Yourself!
- Save a string with
sessionStorage.setItemand read it back withgetItem. - Reload the page and confirm the value is still there.
- Close the tab, open the page again, and confirm the value is gone.
- Store an object using
JSON.stringify, then read it back withJSON.parse.
π§© What Youβve Learned
- β
sessionStorageuses the same API aslocalStorage:setItem,getItem,removeItem, andclear - β Its data is cleared when the tab is closed
- β
Each tab has its own separate
sessionStorage - β
It stores strings only, so use
JSON.stringifyandJSON.parsefor objects - β Choose it for short-lived, per-tab data instead of long-term storage
π Whatβs Next?
Now that you can store temporary data per tab, letβs learn how to read from and write to the userβs clipboard. Continue to Clipboard API.