๐Ÿงฐ Web APIs
Estimated reading: 3 minutes 10 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Web Storage (LocalStorage / SessionStorage)

Or Copy Link

CONTENTS
Scroll to Top