Explain Codes LogoExplain Codes Logo

What happens when localStorage is full?

web-development
localstorage
storage-capacity
best-practices
Alex KataevbyAlex Kataev·Dec 14, 2024
TLDR

If localStorage maxes out, further actions with setItem launch a QuotaExceededError. To ensure your app gracefully handles this, wrap setItem in a try-catch block. The catch block comes into play when the error is sprung, either cleaning out non-essential data or informing the user.

try { localStorage.setItem('key', 'value'); // Trying to stuff more into the cupboards } catch (e) { if (e instanceof DOMException && e.code === 22) { // We've run out of cupboard space, time to notify or free up some room ourselves alert('Storage is full, please clear space. You can\'t fit a gallon into a pint pot!'); // Good old math jokes here } }

In the eyes of different browsers

Different browsers individualize their quota handling. Most often, desktop browsers kick off with a 5MB limit per domain, but not all provide an adjustment knob to the user. Take for instance, Opera may heartily ask the user to enhance the quota, while in Chrome, the quota is as fixed as the North Star.

Errors and how to catch them

Exceeding the storage quota? Expect some exception throwing. Use getItem(key) as your knight in shining armor, retrieving the last peaceably stored value.

Seconds before armageddon

As developers, we need to formulate doomsday strategies for when the localStorage is about to burst. The list includes:

  • Prompting the user—the most respectable approach
  • Sweeping unnecessary or old data under the rug—a roundabout way
  • Storing it server-side or securing a bigger room like IndexDB—expansion plans

No Aunt for automatic cleaning

Unlike our benevolent Aunts, Browsers don't do a free clean-up on localStorage. The oldest data ain't getting any special eviction plan. Implementing your own way? Here's how:

  • Forming your own eviction policy—a scheduled cleaning, maybe?
  • Using timestamping to flag and clear old data—a time-tested approach
  • Employing event listeners for storage babysitting—a power move

Best practices to swear by

To bulletproof your app, adhere to some global best practices. These enlist:

  • Keeping a hawk's eye on the remaining space—like checking your pockets before paying
  • Fixing onerror handlers—like life vests on a ship
  • Educating users about browser-specific behaviors—making them feel in control
  • Putting your app through storage capacity tests, for instance, using the Web Storage Support Test—a fitness check

And finally, making Joker references—like this one. 😜