DEV Community

Renuka Patil
Renuka Patil

Posted on

The main difference between `localStorage` and `sessionStorage`

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!

Top comments (1)

Collapse
 
om4rab profile image
om4rAb

Helpful thank you