Check Total, Used and Remaining Space Available in localStorage
Last updated: December 1, 2022.
The HTML5 localStorage API is an extremely useful way to store data persistently across pages and user sessions.
Only string data can be saved to localStorage and it maxes out at approximately 5 millions characters.
Because Javascript uses UTF-16 character encoding (2 bytes per character), the total space available is approximately 10 MB (per domain).
But how can you test this? And how can you how much you have used / how much is free?
Unfortunately, there is no cross-browser native method for getting total / remaining space.
Instead, you have to get a little creative.
The Solution
The solution below gets the total storage space, used and remaining free space by creating a new item and pushing string data into it until full.
Based on the size of localStorage before the data is pushed (currently used) and the size of localStorage when it maxes out (capacity), it is also possible to calculate space remaining (capacity – current used).
function checkLocalStorage() {
const used = Math.round((JSON.stringify(localStorage).length/1024)*2);
// 'used' is current usage in KB
for (var i = 0, data = "1".repeat(10000); ; i++) {
try { // Pushes another 10000 "1" values in until localStorage maxes out
localStorage.setItem("DATA", data);
data = data + "1".repeat(100000);
} catch(e) {
let total = Math.round((JSON.stringify(localStorage).length/1024)*2);
// 'total' is usage after it maxed out (total capacity)
console.log("Total: " + total + " kB");
console.log("Used: " + used + " kB");
console.log("FREE: " + (total-used) + " kB"); // Uses previous calculations
break;
}
}
localStorage.removeItem('DATA');
// Removes item used to test localStorage after usage
}
checkLocalStorage();
// Example output:
// Total: 10176 kB
// Used: 1953 kB
// FREE: 8223 kB
Check sessionStorage space
The same solution can be used to check sessionStorage space, which has its own storage allocation independent of localStorage:
function checkSessionStorage() {
const used = Math.round((JSON.stringify(sessionStorage).length/1024)*2)
for (var i = 0, data = "1".repeat(10000); ; i++) {
try {
sessionStorage.setItem("DATA", data);
data = data + "1".repeat(100000);
} catch(e) {
var total = Math.round((JSON.stringify(sessionStorage).length/1024)*2);
console.log("Total: " + total + " kB");
console.log("Used: " + used + " kB");
console.log("FREE: " + (total-used) + " kB");
break;
}
}
sessionStorage.removeItem('DATA');
}
checkSessionStorage();
// Example output:
// Total: 10195 kB
// Used: 20 kB
// FREE: 10175 kB
Related links
- A guide to using localStorage and sessionStorage
- Check if a key exists in localStorage
- How to save and retrieve images from localStorage