JavaScript tutorials > Web APIs and the DOM > Browser APIs > How do you use sessionStorage in JavaScript?
How do you use sessionStorage in JavaScript?
This tutorial explains how to use sessionStorage
in JavaScript to store data specific to a browser session. We'll cover setting, getting, and removing data, along with common use cases and best practices.
Introduction to sessionStorage
sessionStorage
is a Web API that allows you to store data for a single session. This means the data is available only while the browser window or tab is open. When the user closes the tab or window, the data is automatically deleted. It's useful for storing temporary data that is only relevant to the current session, such as form data or user preferences.
Setting Data in sessionStorage
To store data in sessionStorage
, use the setItem()
method. It takes two arguments: the key (a string representing the name of the data) and the value (a string representing the data to be stored). Note that sessionStorage
only stores strings. If you need to store objects or arrays, you'll need to serialize them to strings using JSON.stringify()
.
sessionStorage.setItem('username', 'JohnDoe');
sessionStorage.setItem('theme', 'dark');
Getting Data from sessionStorage
To retrieve data from sessionStorage
, use the getItem()
method. It takes one argument: the key of the data you want to retrieve. If the key exists, it returns the corresponding value; otherwise, it returns null
. Remember to parse the string back to its original format using JSON.parse()
if you stored an object or array.
let username = sessionStorage.getItem('username');
let theme = sessionStorage.getItem('theme');
console.log(username); // Output: JohnDoe
console.log(theme); // Output: dark
Removing Data from sessionStorage
You can remove data from sessionStorage
using the removeItem()
method. It takes one argument: the key of the data you want to remove. To clear all data stored in sessionStorage
, use the clear()
method.
sessionStorage.removeItem('username'); // Remove a specific item
sessionStorage.clear(); // Remove all items
Storing Objects with JSON
Since sessionStorage
only stores strings, you need to serialize objects and arrays using JSON.stringify()
before storing them. When retrieving the data, you need to parse the string back to its original format using JSON.parse()
.
let user = {
name: 'John Doe',
age: 30
};
sessionStorage.setItem('user', JSON.stringify(user));
let storedUser = JSON.parse(sessionStorage.getItem('user'));
console.log(storedUser.name); // Output: John Doe
Checking for sessionStorage Support
It's a good practice to check if sessionStorage
is supported by the user's browser before attempting to use it. This can be done by wrapping your sessionStorage
code in a try-catch block. Some browsers might disable sessionStorage
if the user has configured their browser to reject cookies or has disabled JavaScript.
function sessionStorageAvailable() {
try {
sessionStorage.setItem('test', 'test');
sessionStorage.removeItem('test');
return true;
} catch (e) {
return false;
}
}
if (sessionStorageAvailable()) {
console.log('sessionStorage is supported.');
} else {
console.log('sessionStorage is not supported.');
}
Real-Life Use Case: Maintaining Shopping Cart Data
One common use case for sessionStorage
is to maintain shopping cart data. You can store the items added to the cart in sessionStorage
so that if the user navigates to another page or refreshes the page, the cart data is preserved for the duration of the session. Once the user closes the browser, the cart is cleared.
Real-Life Use Case: Wizard Form Progress
Another good use case is saving progress in a multi-step form (wizard). You can store the data entered in each step in sessionStorage
. This allows the user to navigate back and forth between steps without losing their progress within the same session.
Best Practices
sessionStorage
has a limited storage capacity (usually around 5-10 MB). Store only the data that is necessary for the current session.sessionStorage
code in a try-catch block to handle potential errors.sessionStorage
is not a secure storage mechanism. Do not store sensitive information such as passwords or credit card details.
Interview Tip
Be prepared to discuss the differences between sessionStorage
, localStorage
, and cookies in an interview. Understand the use cases for each and their respective limitations. Know that sessionStorage
is session-scoped, localStorage
is persistent, and cookies are sent with every HTTP request.
When to use sessionStorage
Use sessionStorage
when you need to store data that is only relevant to the current browser session, such as temporary user preferences, shopping cart data, or form data. It's ideal for situations where you want the data to be automatically cleared when the user closes the browser or tab.
Memory footprint
sessionStorage
stores data in the browser's memory. Each origin (domain) has a separate sessionStorage
area. The storage capacity is limited (typically 5-10 MB), so it's important to store only essential data to avoid exceeding the limit.
Alternatives
If you need to store data persistently across sessions, consider using localStorage
. If you need to store data on the server-side, you can use cookies or server-side sessions. Consider IndexedDB for larger amounts of structured data.
Pros
sessionStorage
provides a simple and easy-to-use API for storing and retrieving data.
Cons
sessionStorage
has a limited storage capacity compared to other storage mechanisms like IndexedDB.sessionStorage
is not a secure storage mechanism. Do not store sensitive information.
FAQ
-
What is the difference between sessionStorage and localStorage?
sessionStorage
stores data for only one session. The data is deleted when the browser window or tab is closed.localStorage
stores data persistently, meaning it remains available even after the browser is closed and reopened. localStorage data persists until explicitly deleted. -
Is sessionStorage secure?
No,sessionStorage
is not a secure storage mechanism. It is vulnerable to cross-site scripting (XSS) attacks. Do not store sensitive information insessionStorage
. -
What happens if I exceed the sessionStorage storage limit?
If you try to store more data than thesessionStorage
limit allows, thesetItem()
method will throw aQUOTA_EXCEEDED_ERR
exception. You should handle this exception in your code.