Last modified: Jul 20, 2026

JavaScript Session Storage Guide

Session Storage is a powerful feature in modern web browsers. It lets you store data temporarily for a single browser tab or window. This guide explains everything you need to know about using session storage variables in JavaScript.

Unlike cookies, session storage data is not sent to the server. It stays only on the client side. This makes it perfect for storing temporary user preferences or form data.

What Is Session Storage?

Session Storage is part of the Web Storage API. It allows you to save key-value pairs in the browser. The data persists only as long as the browser tab is open.

When you close the tab or window, the data is automatically deleted. This is different from local storage, which keeps data even after the browser is closed.

Session storage is ideal for temporary data like shopping cart items or multi-step form inputs. It helps you create a smoother user experience without server calls.

How to Use Session Storage

Using session storage is simple. You don't need any libraries. The sessionStorage object is available globally in JavaScript.

You can store strings, numbers, and even JSON objects. All values are stored as strings. For objects, you need to use JSON.stringify() and JSON.parse().

Setting a Session Storage Variable

To store a value, use the setItem() method. It takes two arguments: a key and a value.

 
// Set a simple string value
sessionStorage.setItem('username', 'JohnDoe');

// Set a number (stored as string)
sessionStorage.setItem('age', '25');

// Set an object using JSON.stringify
const user = { name: 'Alice', role: 'admin' };
sessionStorage.setItem('userData', JSON.stringify(user));

console.log('Data saved to session storage');

// Output in console:
Data saved to session storage

You can also use dot notation or bracket notation like a variable. But setItem() is the recommended method for clarity.

Getting a Session Storage Variable

To retrieve a value, use the getItem() method. It takes the key as an argument and returns the stored string.

 
// Get a simple string
const username = sessionStorage.getItem('username');
console.log(username); // Output: JohnDoe

// Get and parse an object
const rawData = sessionStorage.getItem('userData');
const userObject = JSON.parse(rawData);
console.log(userObject.name); // Output: Alice

// If key doesn't exist, returns null
const missing = sessionStorage.getItem('nonexistent');
console.log(missing); // Output: null

// Output in console:
JohnDoe
Alice
null

Always check for null when retrieving data. This ensures your code doesn't break if the key is missing.

Removing a Session Storage Variable

To delete a specific variable, use the removeItem() method. It takes the key as an argument.

 
// Remove a single item
sessionStorage.removeItem('age');
console.log(sessionStorage.getItem('age')); // Output: null

// Verify removal
if (sessionStorage.getItem('username')) {
    console.log('Username still exists');
} else {
    console.log('Username removed');
}

// Output in console:
null
Username still exists

Removing items is useful for cleanup. For example, after a user completes a form, you can remove the temporary data.

Clearing All Session Storage

To delete all stored data in the current session, use the clear() method. This removes every key-value pair.

 
// Clear all session storage
sessionStorage.clear();
console.log(sessionStorage.length); // Output: 0

// Check if any data remains
if (sessionStorage.length === 0) {
    console.log('Session storage is now empty');
}

// Output in console:
0
Session storage is now empty

Be careful with clear(). It removes all session data for the current tab. Only use it when you are sure the user no longer needs the data.

Session Storage vs Local Storage

Both session storage and local storage use the same API. The main difference is persistence. Session storage data is cleared when the tab closes. Local storage data remains until you manually delete it.

Choose session storage for temporary data. Use local storage for data that should survive browser restarts, like user preferences or theme settings.

For more on variable storage concepts, check our JavaScript Variable Scope Explained guide.

Practical Examples

Let's look at real-world uses for session storage variables. These examples show how to apply the concepts.

Example 1: Form Data Persistence

Save form data when a user navigates between steps. This prevents data loss if the page reloads.

 
// Save form field value on input change
document.getElementById('email').addEventListener('input', function() {
    sessionStorage.setItem('email', this.value);
});

// Restore value on page load
window.addEventListener('load', function() {
    const savedEmail = sessionStorage.getItem('email');
    if (savedEmail) {
        document.getElementById('email').value = savedEmail;
    }
});

console.log('Form data persistence enabled');

// Output in console:
Form data persistence enabled

Example 2: User Session Tracking

Track whether a user has visited a page during the current session. This is useful for showing welcome messages or tutorials.

 
// Check if user visited before
const hasVisited = sessionStorage.getItem('visitedBefore');

if (!hasVisited) {
    console.log('First visit in this session');
    sessionStorage.setItem('visitedBefore', 'true');
} else {
    console.log('Returning visitor in this session');
}

// Output based on first visit

// Output on first visit:
First visit in this session

// Output on subsequent visits:
Returning visitor in this session

Important Considerations

Session storage has a size limit of about 5-10 MB depending on the browser. Do not store large files or images.

Data is stored as strings only. Always use JSON.stringify() for objects and arrays. Use JSON.parse() when retrieving them.

Session storage is tab-specific. Data in one tab is not accessible from another tab. This is different from local storage, which is shared across tabs.

For naming your variables correctly, refer to our JavaScript Variable Naming Rules guide.

Browser Support

Session storage is supported in all modern browsers. This includes Chrome, Firefox, Safari, Edge, and Opera. It works on mobile browsers too.

For older browsers like Internet Explorer 7, you may need a polyfill. But for most users, session storage is safe to use.

Always test your code in different browsers. Some browsers have slight differences in how they handle storage limits.

Learn more about variable types in our Types of JavaScript Variables guide.

Common Mistakes

Beginners often forget that session storage values are always strings. If you store a number, it becomes a string. You need to convert it back when reading.

Another mistake is using session storage for sensitive data. Never store passwords or credit card numbers in session storage. It is not encrypted.

Also, remember that session storage is cleared when the tab closes. Do not rely on it for permanent data.

Conclusion

JavaScript session storage is a simple and effective way to manage temporary data in your web applications. It helps you create better user experiences without server calls.

You learned how to use setItem(), getItem(), removeItem(), and clear(). You also saw practical examples for form persistence and user tracking.

Remember to always check for null when reading data. Use JSON.stringify() and JSON.parse() for objects. And never store sensitive information.

Session storage is a valuable tool in your JavaScript toolkit. Start using it today to make your web apps more dynamic and user-friendly.