Session storage is a built-in web storage feature in JavaScript that allows websites to save data for the duration of a browser tab session. Unlike localStorage, which keeps data even after closing and reopening the browser, sessionStorage only holds information as long as the tab or window remains open. Once the user closes the tab, the stored data disappears automatically. This makes sessionStorage perfect for temporary data that does not need to persist beyond the current visit, such as form progress, temporary selections, or UI states.
Using sessionStorage, developers can enhance user experience by remembering choices or inputs during a session without the overhead of server-side storage or cookies. It operates through simple key-value pairs, making it easy to store and retrieve strings with just a few JavaScript commands. In this article, we will focus on how to use sessionStorage effectively through real examples, showing you how to create, read, update, and delete session data. We’ll also explore how to store objects and even build a simple page view tracker — all with fun, clear examples featuring characters like Hermione, Ron, and Edward.
Creating and Setting Session Storage Items
To begin storing data in sessionStorage, you use the method sessionStorage.setItem(key, value)
. This command creates a new entry or updates an existing one under the specified key. Both the key and value are strings.
Imagine Hermione is visiting a weather site in Accra, Ghana. She selects “Accra” as her city. The site wants to remember this choice for the current browsing session so that if she moves between pages, the city selection stays intact. Here is how you would set that:
<!DOCTYPE html>
<html>
<head>
<title>Web APIs | Seesion Storage</title>
</head>
<body>
<script>
sessionStorage.setItem("selectedCity", "Accra");
</script>
</body>
</html>
This code stores the key "selectedCity"
with the value "Accra"
in sessionStorage. Now, anywhere else on the site, as long as Hermione keeps her browser tab open, the city name can be retrieved and used to display weather updates or forecasts. This operation is quick and requires just one line of code.
Getting Session Storage Items
Once you’ve saved something in sessionStorage, retrieving it is just as straightforward. The method sessionStorage.getItem(key)
returns the stored value for the given key. If no such key exists, it returns null
.
Suppose Ron wants to retrieve Hermione’s city choice so he can greet her with weather info for Accra. This is how he would do it:
<!DOCTYPE html>
<html>
<head>
<title>Web APIs | Seesion Storage</title>
</head>
<body>
<script>
// sessionStorage.setItem("selectedCity", "Accra");
const city = sessionStorage.getItem("selectedCity");
console.log(`The selected city is: ${city}`);
</script>
</body>
</html>
This code fetches the "selectedCity"
value and prints it to the console. If Hermione had set the city to "Accra"
, this will output:The selected city is: Accra
If the key is not found (for example, if this is Ron’s first visit), the result will be null
. This simple retrieval method allows dynamic updates to the page based on session data.
Updating Session Storage Items
Updating a sessionStorage item means setting a new value for an existing key. The same setItem()
method is used, and it will overwrite the previous value.
Let’s say Chris is browsing a Zambian news site in Lusaka. Initially, he picks English for the news language. Later, he changes his mind and wants French. Here’s how Chris updates his choice:
<!DOCTYPE html>
<html>
<head>
<title>Web APIs | Seesion Storage</title>
</head>
<body>
<script>
sessionStorage.setItem("newsLanguage", "English");
// Later, Chris switches language preference
sessionStorage.setItem("newsLanguage", "French");
</script>
</body>
</html>
The first line sets "newsLanguage"
to "English"
. When the second line runs, the value is replaced with "French"
. Now, all scripts reading "newsLanguage"
will get the new value. This simple overwrite behavior makes sessionStorage very flexible for temporary user preferences.
Removing Specific Items from Session Storage
Sometimes, you want to delete a single sessionStorage item. This is done with sessionStorage.removeItem(key)
. Removing the key deletes its associated value from the storage immediately.
For example, Glenn is logged into his banking dashboard in Nairobi. When he logs out, the site needs to clear his authentication status stored in sessionStorage:
<!DOCTYPE html>
<html>
<head>
<title>Web APIs | Seesion Storage</title>
</head>
<body>
<script>
sessionStorage.setItem("authStatus", "loggedIn");
// When logging out
sessionStorage.removeItem("authStatus");
</script>
</body>
</html>
After calling removeItem("authStatus")
, the key "authStatus"
no longer exists in the sessionStorage. This prevents unauthorized access if the page is revisited during the same session.
Clearing All Session Storage Data
If you want to wipe all data stored in sessionStorage, the sessionStorage.clear()
method erases everything at once. This is useful when resetting a form or ending a user session.
Picture Stewie playing an animal guessing game in Lusaka. After the game finishes, he wants to reset all progress stored in sessionStorage:
<!DOCTYPE html>
<html>
<head>
<title>Web APIs | Seesion Storage</title>
</head>
<body>
<script>
// Clearing all session data after game over
sessionStorage.clear();
</script>
</body>
</html>
Running this command removes every key and value stored during that browser tab session. If the user reloads the page after this, it will be like a fresh start.
Storing and Retrieving Objects (Using JSON)
Session storage only supports strings. So, when you want to save objects or arrays, you need to convert them into a string format first. JavaScript’s JSON.stringify()
method turns an object into a JSON string, and JSON.parse()
converts it back.
Edward runs a coding quiz app in Lusaka. He wants to save a user object in sessionStorage that contains the player’s name and score:
<!DOCTYPE html>
<html>
<head>
<title>Web APIs | Seesion Storage</title>
</head>
<body>
<script>
const user = { name: "Edward", score: 42 };
sessionStorage.setItem("playerData", JSON.stringify(user));
</script>
</body>
</html>
This stores the user data as a string. Later, to retrieve and use this data, Edward does:
<!DOCTYPE html>
<html>
<head>
<title>Web APIs | Seesion Storage</title>
</head>
<body>
<script>
const storedUser = sessionStorage.getItem("playerData");
const userData = storedUser ? JSON.parse(storedUser) : null;
console.log(`${userData.name} scored ${userData.score} points!`);
</script>
</body>
</html>
This code safely retrieves the "playerData"
string, converts it back to an object, and logs the user’s name and score. This technique allows complex data to be temporarily saved during a session.
Writing a Page View Stat Tracker (With sessionStorage)
Session storage is great for tracking data only during the current tab session. Meghan visits a funny cat facts page in Kampala and wants to know how many times she has reloaded the page in this session. We can build a simple view counter using sessionStorage:
<!DOCTYPE html>
<html>
<head>
<title>Web APIs | Seesion Storage</title>
</head>
<body>
<p id="output"></p>
<script>
let pageViews = sessionStorage.getItem("catFactsPageViews");
pageViews = pageViews ? parseInt(pageViews) : 0;
pageViews++;
sessionStorage.setItem("catFactsPageViews", pageViews);
document.getElementById('output').textContent = `You have viewed this page ${pageViews} times during this session.`;
</script>
</body>
</html>
This code reads the current "catFactsPageViews"
value, converts it to a number or starts at 0 if it’s not set. Then, it increments the count and saves it back. Every time Meghan reloads or revisits the page within the same tab, the counter goes up. But once she closes the tab, sessionStorage clears, and the count resets.
Conclusion
JavaScript’s sessionStorage is a simple and powerful tool to store temporary data tied to a browser tab session. You can set and get string values with ease, overwrite existing entries, remove specific keys, or clear everything in one go. By using JSON methods, sessionStorage can even handle objects and arrays. Whether you want to remember a user’s temporary preferences, track page reloads, or store progress in a game, sessionStorage is an essential tool for short-lived, client-side data storage.
References
If you want to learn more about JavaScript sessionStorage and related topics, these resources are excellent starting points:
- MDN Web Docs:
Window.sessionStorage
The official documentation explaining sessionStorage and how it works. - MDN Web Docs: Web Storage API
A broader look at both sessionStorage and localStorage APIs. - MDN Web Docs:
JSON.stringify()
Learn how to convert objects to strings for storage. - MDN Web Docs:
JSON.parse()
How to parse JSON strings back into JavaScript objects.