What is the max size of localStorage values?
The localStorage
feature in HTML5 is handy, but it's far from unlimited. A ballpark figure you can work with is up to 5MB
per origin, or website. However, you can arm yourself with a nifty tool to find the actual limit in varying browsers. Here's a snippet of JavaScript code that uses the "how much can you eat before you're full" principle:
The above method will progressively test and give you an upper limit of your localStorage
capacity.
Size according to different browsers (aka. "every browser has its own appetite")
The storage limit is browser-dependent, and typically, here are the quantities they can gobble up:
- Google Chrome, Mozilla Firefox, Opera: Roughly
10MB
per origin. - Internet Explorer: Around
10MB
per storage area. - Mozilla Firefox default domain size: Capped at
5120KB
.
Remember, don't take these numbers as gospel. Different versions, settings, and especially browsers can skew these numbers.
What can you store and how (aka. "don't try to force a pizza into a bottle")
This is important: localStorage
only deals with strings
. That means, if you have complex data types to store, like objects, you'll need to convert them to strings before you start the storage process. Here's how to do that:
Then later you can retrieve it with:
Please remember that this "stringification" can push you a bit nearer to your storage limit than you'd like, due to the added information that comes with string representations.
Strategies to tuck more into localStorage (aka. "how to make your pants bigger")
Compress before storage
Try compressing your string data before storing it. There are handy tools like LZ-String
that help you squeeze more data into localStorage
.
Be ready for QuotaExceededError
Always build your web application in a way that anticipates localStorage
capacity limits. One way is to check whether 'localStorage' is available and catch exceptions during set operations. The QuotaExceededError
is thrown when there's no space left in the localStorage - make sure you catch it and handle it elegantly.
Implement data eviction policies
Have a plan for managing data when your storage limit is reached. You might need to implement a "clean-up crew" that decides which data to delete when you run out of storage.
Best practices in localStorage usage
Cater for different browsers
Because there's no one-size-fits-all limit across browsers, consider the variability and be ready to test your app in multiple browsers.
Look for and handle storage full errors
Recall the QuotaExceededError
from earlier? Build your code to anticipate and capture it when it's thrown. This can prompt a cleanup action or alert the user to free up some space.
Regular verification
Updating versions, changing browsers, fluctuating user settings - all these can alter your storage limit. Make it a routine to verify your storage limits.
Was this article helpful?