DEV Community

Cover image for Understanding LocalStorage vs sessionStorage in Web Development
balaji s
balaji s

Posted on

Understanding LocalStorage vs sessionStorage in Web Development

A Complete Guide to Saving and retriving Data in the Browser using Web Storage API

When building websites, web developers often need a way to store data right inside the user's browser. Before modern HTML5, this meant relying heavily on cookies. Today, we have two much better, cleaner options: LocalStorage and sessionStorage.

Both belong to the Web Storage API and let you save key-value pairs. But how do you know when to use which? Let's dive in from the basics to advanced concepts with clear, simple examples!


The Basics (What Are They?)

Think of both localStorage and sessionStorage as mini-databases inside your web browser. They both use the exact same methods to save, read, and delete data.

  • LocalStorage: Data stored here never expires. Even if you close the browser tab, restart your computer, or come back a week later, the data will still be there until you manually delete it via code or clear your browser history.
  • sessionStorage: Data stored here lasts only as long as the browser tab is open. The moment you close that specific tab or window, the data is wiped out instantly.

How to Use Them

The syntax for both is identical. Just swap out localStorage for sessionStorage depending on your needs.

1. Saving Data (setItem)

To save data, use .setItem('key', 'value').

// Save user settings in LocalStorage (stays forever)
localStorage.setItem('theme', 'dark');

// Save a temporary form step in sessionStorage (disappears when tab closes)
sessionStorage.setItem('currentStep', '2');

Enter fullscreen mode Exit fullscreen mode

2. Reading Data (getItem)

To retrieve what you saved, use .getItem('key').

// Get the saved theme
const userTheme = localStorage.getItem('theme');
console.log(userTheme); // Output: "dark"

Enter fullscreen mode Exit fullscreen mode

3. Removing Data (removeItem)

To delete a specific piece of data:

localStorage.removeItem('theme');

Enter fullscreen mode Exit fullscreen mode

4. Clearing Everything (clear)

To wipe out all data stored for your website:

// Clears everything in sessionStorage for this site
sessionStorage.clear();

Enter fullscreen mode Exit fullscreen mode

Advanced Concepts

Now that you know the basics, let's look at how professionals handle real-world data structures, security, and storage limits.

1. Storing Objects and Arrays (JSON)

Web storage can only save strings. If you try to save a JavaScript object or array directly, it will save as the text "[object Object]", which is useless.

To fix this, use JSON.stringify() when saving and JSON.parse() when reading.

// The Object we want to save
const user = {
  name: 'Aarav',
  age: 25,
  isLoggedIn: true
};

// 1.Save as a JSON string
localStorage.setItem('userData', JSON.stringify(user));

// 2.Retrieve and convert back to an Object
const savedUser = JSON.parse(localStorage.getItem('userData'));

console.log(savedUser.name); // Output: Aarav

Enter fullscreen mode Exit fullscreen mode

2. Listening for Changes (storage event)

LocalStorage has a cool superpower: it can trigger events across different tabs of the same website! If a user has your site open in two tabs and changes their theme in Tab A, Tab B can automatically detect it and update.

Note: This only works for localStorage, not sessionStorage.

// Run this code in your script to listen for storage changes from other tabs
window.addEventListener('storage', (event) => {
  if (event.key === 'theme') {
    console.log(`Theme changed to: ${event.newValue}`);
    // Apply new theme instantly without refreshing the page!
  }
});

Enter fullscreen mode Exit fullscreen mode

3. Storage Limits & Security (What to watch out for)

  • Storage Capacity: Both typically allow around 5MB to 10MB of data per domain. That's plenty for text, settings, and small JSON objects, but don't try to store large files or images!
  • Security Warning: Never store sensitive data like passwords, credit card numbers, or personal identification tokens in LocalStorage or sessionStorage. Anything stored there can be accessed by any malicious JavaScript script running on your page (via Cross-Site Scripting or XSS attacks).

Summary

Feature LocalStorage sessionStorage
Lifespan Forever (until cleared manually) Until the tab/window is closed
Scope Shared across all tabs/windows of the same site Isolated to that specific tab only
Capacity ~5MB - 10MB ~5MB - 10MB
Best Used For Dark mode preferences, user settings, offline cached data Shopping cart temporary steps, multi-step form data

Conclusion

Choosing between localStorage and sessionStorage is simple: Ask yourself, "Does this data need to survive if the user closes the tab?"

  • If yes, use localStorage.
  • If no (it's temporary), use sessionStorage.

let me share your doubts about in this blog to put commands below

Top comments (0)