Explain Codes LogoExplain Codes Logo

When is localStorage cleared?

javascript
localstorage
indexeddb
data-persistence
Alex KataevbyAlex Kataev·Aug 9, 2024
TLDR

The data stored in localStorage remains untouched and unexpired until it's explicitly cleared by user actions via browser settings, script executions using localStorage.clear() or localStorage.removeItem('key') methods, or when the browser decides to perform a purge due the reaching of space limits or entering privacy mode.

Notable exceptions to persistence

While localStorage aims for long-term persistence, poorly timed interventions or accidental circumstances can lead to unexpected data clearance:

  • Browser or OS upgrades: Some significant system updates can cause all localStorage to vanish into the digital void.
  • Programmatic apocalypse: Yes, JavaScript can turn into a destroyer of worlds - or localStorage data for that matter.
  • Bulging boundaries: When localStorage gets chubby, browsers might start trimming down the excess data under their eviction policies.

Edge cases and golden practices

Utilizing localStorage, the saying "forewarned is forearmed" holds true. It's essential to keep in mind some edge cases along with golden principles for optimal usage:

  • Capacity planning: Since localStorage allowances might be distributed across multiple domains, you could potentially run into space-related issues.
  • Script safeguards: Avoid going berserk with data; always check storage room before unleashing data tsunamis.
  • Data defense: Given localStorage can be cleared, keep a server sync or backup plan handy to recover lost data.

Browser-specific quirks

Even though localStorage is a global phenomenon, its handling echoes the browser's individuality:

  • Firefox: The red panda growls when cookies are no more, clearing localStorage for dinner.
  • Chrome: A shiny beacon of data clearance, localStorage included, when "Clear Browsing Data" and "Cookies and Other Site Data" are selected.
  • Opera: Offers interesting reads on localStorage but lacks clear user instructions on data clearance.

Limits, evictions, and 5-Star Hotels

localStorage might seem like luxury digital real estate, but it’s not without limits or eviction policies:

  • Minimum limit: A guaranteed 5MB per domain on most occasions like a cozy suite.
  • Maximum potential: Depending on the browser's generosity, a domain might get a 1GB 5-star deluxe room.
  • Eviction: When your luggage (read data) gets too much, the hotel (read browser) may help clear some space, favoring the latest check-ins (LRU Policy).

IndexedDB - The step-up Apartment

When localStorage starts to feel cramped, IndexedDB might just be the spacious apartment you need. It opens the doorway to 80% of disk space, a true luxury for your massive and structured data needs.