Web Storage API: LocalStorage vs. SessionStorage

Web Storage API: LocalStorage vs. SessionStorage

When developing modern web applications, it’s common to store some data directly on the user's browser. Whether it’s user preferences, session data, or temporary information, client-side storage is a powerful tool.

Not too long ago, cookies were the only way to do this, and that came with various limitations and security concerns. Lucky for us, we now have more options. Two widely used storage solutions provided by the Web Storage API are LocalStorage and SessionStorage

In this article, I shall break down what each of these methods does, the key differences between them, and scenarios where you’d want to use one over the other. By the end, you’ll have a clear understanding of how to leverage these tools in your web applications.

What is the Web Storage API?

The Web Storage API is a specification that allows developers to store key-value pairs in a web browser without needing to send that data to a server. Unlike cookies, which are sent with every HTTP request, Web Storage data remains within the browser and is never transmitted automatically.

It offers two types of storage mechanisms, LocalStorage and SessionStorage and each has its own use case and behavior, allowing you to choose based on your specific requirements.

Understanding LocalStorage

Let's first breakdown LocalStorage.

LocalStorage is a persistent storage mechanism that saves data with no expiration date or time. Once data is stored in LocalStorage, it will remain there until it is explicitly removed by the user or programmatically via JavaScript.

Key Features of LocalStorage:

Persistent storage: Data saved in LocalStorage is not deleted when the browser or tab is closed. It persists across sessions and even across different tabs or windows opened for the same domain.

Storage limit: Most modern browsers allocate around 5MB of storage per origin.

Simple API: Interacting with LocalStorage is straightforward using simple JavaScript methods. (Examples down below)

No expiration: Data will remain in LocalStorage indefinitely until it's manually cleared by code or by the user.

Example Use Cases:

LocalStorage is great for storing user preferences locally on device. You can think of dark/light mode selections, language settings or any type of customization that your website offers to users.

You can also leverage LocalStorage for caching any type of expensive data, where it would make more sense to pull once and then read locally to improve load times. This of course makes more sense if the data in question does not update frequently. And if it falls under the size limitations of LocalStorage.

Example:

// Saving data to LocalStorage
localStorage.setItem('username', 'JohnDoe');

// Retrieving data from LocalStorage
let user = localStorage.getItem('username');
console.log(user); // Output: JohnDoe

// Removing a specific item
localStorage.removeItem('username');

// Clearing all data in LocalStorage
localStorage.clear();

Understanding SessionStorage

On the other hand, SessionStorage is designed to store data only for the duration of the page session. As soon as the tab or window is closed, the data is cleared automatically.

Key Features of SessionStorage:

Session-based: SessionStorage data only persists while the page session is active. It is automatically cleared when the user closes the tab or window.

Same origin: Just like LocalStorage, the data is specific to a particular domain.

Separate for each tab: Unlike LocalStorage, which can be shared across multiple tabs, SessionStorage data is isolated per tab.

Storage limit: The size limit is also around 5MB per origin, but really depends on the browser.

Example Use Cases:

SessionStorage comes in handy when you only need a user's data for a short period of time, such as filling out a multi-step form where the final submission is saved for the very end.

And not as commonly seen, SessionStorage works great for authentication when it is limited in scope to a single instance of a tab. You can think of some kind of online test, where users are presented with the questions in a single session that expires after some time.

Example:

// Saving data to SessionStorage
sessionStorage.setItem('authToken', 'abcdef12345');

// Retrieving data from SessionStorage
let token = sessionStorage.getItem('authToken');
console.log(token); // Output: abcdef12345

// Removing a specific item
sessionStorage.removeItem('authToken');

// Clearing all data in SessionStorage
sessionStorage.clear();

Key Differences Between LocalStorage and SessionStorage

Although LocalStorage and SessionStorage share a similar API and storage limits, their core differences lie in the scope and lifetime of the stored data. Which of course impacts their specific use cases as well.

Feature LocalStorage SessionStorage
Data persistence Persistent across sessions, even after closing tabs Cleared when the tab or window is closed
Scope Shared across multiple tabs/windows of the same domain Unique to each tab or window
Size limit 5MB (varies slightly by browser) 5MB (varies slightly by browser)
Expiration None (until manually deleted) Expires at the end of the session
Use case Ideal for long-term storage of user preferences, caching Ideal for temporary storage, session tokens, and form data

When to Use LocalStorage vs. SessionStorage

Choosing between LocalStorage and SessionStorage depends on the type of data that you are working with and the specific use case.

Use LocalStorage when:

You need to store data that should persist across multiple sessions, such as user settings or site preferences.

You're working with data that should be shared across tabs for the same domain.

You want to cache data for performance optimization, reducing the need for repeated network requests.

Use SessionStorage when:

You’re dealing with data that should only persist during the current session, like form entries in a multi-step process.

You need separation between different tabs or windows, ensuring that data is isolated per session.

You’re storing sensitive information like session tokens, which should only last as long as the browser tab is open.

Security Considerations

While both LocalStorage and SessionStorage are great for client-side storage, be mindful of potential security risks.

Not secure for sensitive data: Since data stored in LocalStorage and SessionStorage is accessible via JavaScript, it’s crucial not to store sensitive information (such as passwords or credit card numbers) in them. Cross-Site Scripting (XSS) attacks can easily expose this data.

Consider encryption: If you must store sensitive data, consider encrypting it before saving it to Web Storage.

Clear storage when not needed: Ensure that you properly clear storage when data is no longer necessary, especially for SessionStorage where leaving sensitive session data hanging around could lead to security leaks.

Conclusion

Both LocalStorage and SessionStorage are useful tools for managing client-side data, but they serve different purposes. LocalStorage is perfect for storing long-term data, like user preferences or cached content, while SessionStorage is designed for temporary, session-specific storage.

Understanding the key differences will allow you to use the right tool for the job and build more efficient, responsive web applications. Next time you're developing a web app, remember to leverage these two tools to enhance user experience and optimize data handling.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet

Add a comment