๐Ÿงฐ Web APIs
Estimated reading: 3 minutes 263 views

JavaScript Web Storage: LocalStorage vs SessionStorage Explained with Examples


Introduction โ€“ Why Web Storage Is Essential

Every modern web application needs to store dataโ€”be it login tokens, user preferences, or form progress. But how do we store this data without relying on a backend?

Enter the JavaScript Web Storage API, which provides two main tools:

  • localStorage โ€“ Persistent data storage across browser sessions
  • sessionStorage โ€“ Temporary data storage limited to the session/tab

By the end of this article, you’ll learn:

The key differences between localStorage and sessionStorage
How to store, retrieve, and delete data in both
Best practices for usage, performance, and security
Frequently asked questions with real-world clarifications


What is Web Storage API?

The Web Storage API allows you to store keyโ€“value pairs in a user’s browser. It’s a cleaner, more intuitive alternative to cookies for storing client-side data.

Web Storage includes two objects:

Storage TypeScopeExpiryShared Across Tabs
localStoragePersistentNever (manual) Yes
sessionStoragePer-tab / per-sessionOn tab close No

Note: Both store string-only data. You must serialize objects using JSON.stringify().


localStorage โ€“ Persistent Client Storage

localStorage stores data with no expiration. Data remains even after the browser is closed and reopened.

Basic Usage

// Store data
localStorage.setItem('username', 'vaibhav');

// Retrieve data
let user = localStorage.getItem('username');
console.log(user); // "vaibhav"

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

// Clear all items
localStorage.clear();

Storing Objects in localStorage

const settings = { theme: 'dark', fontSize: '16px' };
localStorage.setItem('settings', JSON.stringify(settings));

const saved = JSON.parse(localStorage.getItem('settings'));
console.log(saved.theme); // "dark"

Note: You must use JSON.stringify() and JSON.parse() for storing non-primitive values.


sessionStorage โ€“ Temporary Per-Session Storage

sessionStorage stores data until the tab or browser window is closed. Ideal for sensitive or tab-specific data.

Basic Usage

// Store data
sessionStorage.setItem('cart', '3 items');

// Retrieve data
let cartItems = sessionStorage.getItem('cart');
console.log(cartItems); // "3 items"

// Remove item
sessionStorage.removeItem('cart');

// Clear all
sessionStorage.clear();

Tip: Each browser tab gets its own isolated sessionStorage. Refreshing a tab retains the data, but closing it removes it.


Use Cases Comparison

Use CaseBest Storage
Login tokens or persistent loginlocalStorage
Tab-specific form progresssessionStorage
Theme or layout preferenceslocalStorage
Shopping cart (per tab)sessionStorage
Caching API response temporarilyEither (contextual)

Web Storage: Best Practices

๐ŸŸฉ Dos:

  • Serialize objects using JSON.stringify()
  • Check for storage availability before using
  • Use try...catch for safer operations
if (typeof(Storage) !== "undefined") {
  // Safe to use localStorage or sessionStorage
}

๐ŸŸฅ Don’ts:

  • Donโ€™t store sensitive data (e.g., passwords, tokens)
  • Donโ€™t exceed size limits (~5MB depending on the browser)
  • Donโ€™t rely on storage for critical logic (users may clear it)

Browser Compatibility

Web Storage API is supported in all modern browsers, including Chrome, Firefox, Edge, Safari, and Opera.

BrowserlocalStoragesessionStorage
Chrome
Firefox
Safari
Edge
Opera

Summary โ€“ Which Should You Use?

CriteriaUse localStorageUse sessionStorage
ExpiryNever (manual clear)On tab/browser close
ScopeShared across tabs/windowsSpecific to one tab/session
Use forPreferences, auth, cacheTab-sensitive data, temp info
Security Prone to XSS if misusedBetter for sensitive session info

FAQ โ€“ Web Storage Essentials

What is the size limit for localStorage and sessionStorage?
Typically around 5MB per origin. Varies slightly by browser.

Can I store JavaScript objects directly?
No, only strings can be stored. Use JSON.stringify() and JSON.parse().

Is localStorage secure?
No. It’s accessible via JavaScript, so avoid storing sensitive data like passwords or tokens.

Will sessionStorage persist on page refresh?
Yes, but it clears when the tab or window is closed.

Is Web Storage faster than cookies?
Yes. Itโ€™s synchronous and avoids HTTP overhead, unlike cookies which are sent with every request.


Share Now :
Share

Web Storage (LocalStorage / SessionStorage)

Or Copy Link

CONTENTS
Scroll to Top