How to see localStorage usage

How to see localStorage usage

Find localStorage troublemakers quickly and easily

window.localStorage is great for persisting data in the browser on the client side. But browsers limit the local storage to hold only 5 MB. Due to this limit, big chunks of data can easily exceed the limit. Local storage is therefore used largely for persisting non-sensitive configurations, e.g. to remember user decisions like light/dark mode, settings, and the state of app UI.

If exceeded, you'll see this warning:

localStorage exceeded

The warning tells us that recipes item is exceeding localStorage. But we don't know if this item is the biggest sinner in terms of storage usage. recipes might not even be a problem. On top of this, the application will stop running if this error is not handled.

Currently, seeing information on how much storage each item in local storage is taking up is not possible using the dev tools:

We can see the data, but not how much storage each entry is using. One option is to copy data objects and check their size using some online tool. But you'll have to do this for each item. This can get quite cumbersome.

But fear not! I've made this piece of JavaScript code. Either throw it in the browser dev tools console or your codebase, and you'll see a nice overview of your local storage usage, and which items are the biggest sinners.

// paste into dev tools console
const checkLocalStorage = () => {
    console.log(
        "%clocalStorage Usage",
        `font-weight: bold; color: grey; 
        padding: 5px; border-top: solid 2px grey;
        border-bottom: solid 2px grey; margin-top: 10px`
    );

    let total = 0;
    for (const item in localStorage) {
        let amount = (localStorage[item].length * 2) / 1024 / 1024;
        if (isNaN(amount) || amount < 0.00001) continue;
        total += amount;

        let color = "green";
        if (amount > 0.3) {
            color = "red";
        } else if (amount > 0.1) {
            color = "orange";
        }
        console.log(`%c${item} = ${amount.toFixed(4)} MB`, `color: ${color}`);
    }
    console.log(
        "%c TOTAL: " + total.toFixed(2) + " MB ",
        "font-weight: bold; color: lightblue; padding: 5px;"
    );
};
checkLocalStorage();

In action:

Running this code snippet quickly shows the biggest troublemakers. shop-items take up ~1.5 MB, and posts take up ~3 MB. These massive objects should probably be persisted another way, e.g. using indexedDB, moved to the backend or just don't store the full dataset in the browser.

I've uploaded the code as a gist right here.

Let me know if you know other cool tricks on how to inspect local storage usage :-)