JavaScript Session Storage

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.

session-storage.js
sessionStorage.setItem("step", "2"); // save a value
const step = sessionStorage.getItem("step"); // read it back
console.log(step); // "2"
sessionStorage.removeItem("step"); // delete one key
sessionStorage.clear(); // delete everything

Let’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 in step, which logs "2".
  • removeItem("step") deletes just the "step" key.
  • clear() wipes every key in this tab’s sessionStorage.

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.

session-storage.js
// βœ… Save a value for this tab session
sessionStorage.setItem("username", "Alex");
// Read it back later, even after a page reload
const 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 the username variable, 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.

session-storage.js
const filters = { category: "books", inStock: true };
// βœ… Convert the object to a string before saving
sessionStorage.setItem("filters", JSON.stringify(filters));
// βœ… Parse the string back into an object when reading
const saved = JSON.parse(sessionStorage.getItem("filters"));
console.log(saved.category); // "books"

Let’s trace the round trip:

  • We start with a filters object holding a category and an in-stock flag.
  • JSON.stringify(filters) turns that object into a string, which setItem then saves under "filters".
  • getItem("filters") reads the string back, and JSON.parse rebuilds it into a real object stored in saved.
  • saved.category reads 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.

session-storage.js
// ❌ 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.

session-storage.js
// Remember which step of a multi-step form the user is on
function 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()); // 3

Here is how this code works:

  • saveStep takes a step number and saves it under the key "formStep".
  • loadStep reads that value back, wraps it in Number(...) to turn the stored string into a number, and falls back to 1 with || 1 when nothing is saved yet.
  • Calling saveStep(3) then loadStep() stores step 3 and reads it back, logging 3.

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!

  1. Save a string with sessionStorage.setItem and read it back with getItem.
  2. Reload the page and confirm the value is still there.
  3. Close the tab, open the page again, and confirm the value is gone.
  4. Store an object using JSON.stringify, then read it back with JSON.parse.

🧩 What You’ve Learned

  • βœ… sessionStorage uses the same API as localStorage: setItem, getItem, removeItem, and clear
  • βœ… Its data is cleared when the tab is closed
  • βœ… Each tab has its own separate sessionStorage
  • βœ… It stores strings only, so use JSON.stringify and JSON.parse for 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.

Share & Connect