The main difference between `localStorage` and `sessionStorage`
Renuka Patil

Renuka Patil @renukapatil

About: Interested in cloud computing, DevOps and microservices.

Location:
Pune, India
Joined:
Mar 7, 2022

The main difference between `localStorage` and `sessionStorage`

Publish Date: Jul 7
8 1

The main difference between localStorage and sessionStorage lies in how long the data is stored and where it's accessible. Here's a detailed comparison:


🗂️ 1. Persistence Duration

Feature localStorage sessionStorage
Lifespan Persists even after the browser/tab is closed Data is cleared when the tab is closed
Use Case For data that should persist between sessions For temporary data needed during a session

🌐 2. Scope of Access

Feature localStorage sessionStorage
Tab/Window Sharing Shared across all tabs/windows from the same origin Unique to the specific tab or window
Example Login token accessible in all tabs Shopping cart limited to one tab

📦 3. Storage Capacity

Feature localStorage & sessionStorage
Capacity Around 5MB (varies by browser)
Storage Type Stores only strings

To store objects:

// Storing
localStorage.setItem("user", JSON.stringify(userObj));

// Retrieving
const user = JSON.parse(localStorage.getItem("user") || '{}');
Enter fullscreen mode Exit fullscreen mode

🔐 4. Security

  • Both are vulnerable to XSS (Cross-Site Scripting) attacks.
  • Neither should store sensitive data like passwords directly.

✅ When to Use Which?

Use Case Recommended Storage
Login sessions that persist on refresh localStorage
Temporary form data within one tab sessionStorage
Remembering user preferences/settings localStorage
One-time flow data (e.g., survey step) sessionStorage

Summary

Feature localStorage sessionStorage
Persist Across Tabs ✅ Yes ❌ No
Persist After Refresh ✅ Yes ✅ Yes
Persist After Closing Tab ✅ Yes ❌ No
Use Case Long-term storage Tab/session-specific

Happy Coding!

Comments 1 total

  • om4rAb
    om4rAbJul 24, 2025

    Helpful thank you

Add comment