A web application may work perfectly during development and still fail when users start storing large amounts of data. This often happens in applications that support offline access, save form information locally, download files, or cache images and other resources.
Consider a document management application. A user opens the application, downloads several documents, and continues working without an internet connection. The application stores the downloaded files and changes in browser storage so the user can access them later.
After some time, the browser runs out of space available to that application. The user edits another document and presses Save, but the browser cannot store the changes. If the application does not handle this situation properly, the user may lose important work.
This is not an unusual problem. Browser storage has limits, and those limits can depend on the browser, device, available disk space, and storage policies. Developers cannot assume that IndexedDB, Cache Storage, or localStorage will always have enough space.
The solution is not simply to increase the storage limit. Web applications need to understand how browser storage works, check available space when useful, handle storage errors, and decide which data can safely be removed.
This article explains how to build applications that continue working when browser storage is nearly full or completely exhausted.
Understanding Browser Storage Limits
Browsers provide several ways to store information on a user's device. The most common options include localStorage, sessionStorage, IndexedDB, and Cache Storage.
Each option has a different purpose, and they do not all have the same storage limits.
For example, localStorage is useful for small values such as user preferences, selected themes, and simple application settings. IndexedDB is more suitable for larger structured data, including offline records and application content. Cache Storage is commonly used by service workers to store network responses and static resources.
The important thing to understand is that browser storage is not unlimited.
The browser decides how much storage an application can use. The available space can change depending on the device and browser conditions. Private browsing modes may also apply different limits or remove stored data when the private session ends.
There is no single storage limit that developers can safely assume across all browsers.
Another important detail is that storage is generally managed at the origin level. An origin includes the protocol, hostname, and port. Data stored by different applications or subdomains may therefore have separate storage arrangements.
When the storage limit is reached, attempts to write more data can fail with a QuotaExceededError.
This error can occur when writing to IndexedDB, Cache Storage, or Web Storage. The application should handle it instead of assuming that every storage operation will succeed.
Check How Much Storage the Application Is Using
Before saving large amounts of data, it is useful to understand how much browser storage the application is already using.
The browser provides the StorageManager API for this purpose. Its estimate() method returns an approximate storage usage and quota for the current origin.
async function checkStorageUsage() {
if (!navigator.storage ||
!navigator.storage.estimate) {
console.log("Storage estimate is not supported.");
return null;
}
try {
const estimate = await navigator.storage.estimate();
const usage = estimate.usage ?? 0;
const quota = estimate.quota ?? 0;
const remaining = Math.max(0, quota - usage);
return {
usage,
quota,
remaining
};
} catch (error) {
console.error("Unable to estimate storage:", error);
return null;
}
}
The function checks whether the API is available before using it. It then reads the estimated usage and quota values.
You can call it before downloading a large file or saving a collection of offline records:
const storage = await checkStorageUsage();
if (storage) {
console.log("Storage used:", storage.usage);
console.log("Estimated quota:", storage.quota);
console.log("Estimated remaining:", storage.remaining);
}
All these values are measured in bytes.
For a user-friendly display, convert them into megabytes:
function formatMegabytes(bytes) {
return (bytes / (1024 * 1024)).toFixed(2) + " MB";
}
For example, the application could display:
Storage used: 450.25 MB
Estimated quota: 1024.00 MB
Estimated remaining: 573.75 MB
These values are only estimates. The browser may use compression, deduplication, or other storage management techniques. The available quota can also change after the estimate is returned.
Therefore, do not use this information as a guarantee that the next storage operation will succeed.
It is useful for showing storage information and warning users before large downloads, but every important write operation must still handle errors.
Handle QuotaExceededError in localStorage
The simplest place to understand storage failures is localStorage.
Suppose an application saves recently viewed documents:
function saveRecentDocuments(documents) {
localStorage.setItem(
"recentDocuments",
JSON.stringify(documents)
);
}
This code works as long as the browser can store the supplied value. However, if the storage limit has been reached, setItem() can throw a QuotaExceededError.
Without error handling, the exception can interrupt the application flow.
A better implementation is:
function saveRecentDocuments(documents) {
try {
localStorage.setItem(
"recentDocuments",
JSON.stringify(documents)
);
return true;
} catch (error) {
if (error.name === "QuotaExceededError") {
console.error("Browser storage is full.");
return false;
}
throw error;
}
}
Now the application can respond when storage is full instead of allowing the error to interrupt the operation.
For example, it could show a message asking the user to remove old downloaded content or reduce the amount of locally stored information.
However, there is an important design decision here. If recent documents are only used to improve navigation, the application may safely remove older entries. If the same storage contains unsynchronized user changes, deleting records automatically could result in data loss.
Always understand the purpose of the data before deciding how to recover from a storage failure.
Handle Storage Failures in IndexedDB
IndexedDB is commonly used when applications need to store structured data for offline access.
Unlike localStorage, IndexedDB operations are asynchronous and use transactions. This makes it more suitable for larger application data, but developers still need to handle transaction failures.
Consider an application that saves offline orders.
A simplified object store might contain records such as:
{
id: "order-1001",
customerName: "Rahul",
total: 2500,
syncStatus: "pending"
}
The application can save an order using a readwrite transaction.
function saveOrder(database, order) {
return new Promise((resolve, reject) => {
const transaction = database.transaction(
"orders",
"readwrite"
);
const store = transaction.objectStore("orders");
store.put(order);
transaction.oncomplete = () => {
resolve(true);
};
transaction.onabort = () => {
const error = transaction.error;
if (error?.name === "QuotaExceededError") {
reject(new Error(
"Browser storage is full. The order could not be saved locally."
));
return;
}
reject(error || new Error("Order transaction was aborted."));
};
transaction.onerror = () => {
reject(transaction.error || new Error(
"Unable to save the order."
));
};
});
}
The important part is transaction.onabort. When a storage write cannot be completed because the quota has been exceeded, the transaction can be aborted.
The application should treat the transaction as failed and should not report that the order was saved.
There is another important detail: IndexedDB transactions are atomic. If a transaction contains several changes and it is aborted, those changes are not committed.
For this reason, do not perform unrelated work inside one large transaction. Keep transactions focused on the records that need to be saved together.
Also, remember that transaction.onerror and transaction.onabort are related events. A transaction may produce an error and then be aborted. Avoid displaying duplicate error messages from both handlers.
Handle Storage Errors in Cache Storage
Progressive Web Apps commonly use Cache Storage to save application files and network responses.
For example, a service worker may cache images, stylesheets, JavaScript files, and API responses.
Consider this code:
async function cacheImage(imageUrl) {
const cache = await caches.open("app-images-v1");
await cache.add(imageUrl);
}
If the browser does not have enough storage space, the cache operation may fail.
The application should catch that error:
async function cacheImage(imageUrl) {
try {
const cache = await caches.open("app-images-v1");
await cache.add(imageUrl);
return true;
} catch (error) {
if (error.name === "QuotaExceededError") {
console.error("Unable to cache image. Storage is full.");
return false;
}
console.error("Image caching failed:", error);
return false;
}
}
This prevents a failed cache operation from unexpectedly breaking other application functionality.
Not every cached resource has the same importance. Application files required to load the PWA may be more important than old images or temporary API responses.
That difference should guide the cleanup strategy.
Remove Old Cache Entries Without Breaking the Application
One practical way to recover storage is to remove resources that the application no longer needs.
For example, an application may have several old image cache versions left behind after multiple deployments.
A cleanup function can remove an older cache:
async function removeOldImageCache() {
const cacheNames = await caches.keys();
const oldCaches = cacheNames.filter(name =>
name.startsWith("app-images-v")
);
for (const cacheName of oldCaches) {
if (cacheName !== "app-images-v3") {
await caches.delete(cacheName);
}
}
}
This example keeps the current image cache and deletes older versions.
However, cache cleanup should be designed carefully.
Do not delete every cache just because storage is full. A service worker may depend on cached application files to load the application when the user is offline.
A better approach is to separate caches by purpose.
For example:
Cache | Purpose | Cleanup priority |
|---|
Application shell | Required files for loading the application | Very low |
User images | Downloaded images | Medium |
Temporary API responses | Data that can be downloaded again | High |
Old application versions | Resources no longer used | High |
This makes it easier to remove temporary resources without affecting the core application.
Also, cache deletion should be based on actual cache ownership. Do not delete unrelated cache names that may belong to another part of the application.
Decide Which Data Can Be Removed
When browser storage is full, the application needs a clear rule for deciding what to delete.
This is where many implementations make mistakes. They remove the oldest records without checking whether those records are still important.
For example, an offline note-taking application may contain three types of data:
Notes that have already been synchronized with the server.
Notes that are waiting to be synchronized.
Temporary images downloaded for previews.
These records should not be treated equally.
A synchronized note can usually be downloaded again from the server. A temporary preview image can also be downloaded again. However, an unsynchronized note may exist only on the user's device.
Removing that note could permanently destroy the user's work.
A practical cleanup strategy should follow the importance of the data.
Start with temporary files and old cache entries. Next, consider removing downloaded resources that can be downloaded again. If the application has old synchronized records, allow the user to remove them when appropriate.
Keep unsynchronized user changes protected until the server confirms that they have been saved.
For applications that support offline editing, it is also useful to maintain a visible synchronization status. Users should be able to distinguish between saved changes, pending changes, and changes that could not be saved.
Request Persistent Storage for Important Applications
By default, browser storage is generally treated as best-effort storage. This means the browser may remove stored data when storage pressure occurs.
For applications that rely heavily on local data, developers can request persistent storage through the Storage API.
The browser provides navigator.storage.persist() for this purpose.
async function requestPersistentStorage() {
if (!navigator.storage ||
!navigator.storage.persist) {
return false;
}
try {
const granted = await navigator.storage.persist();
if (granted) {
console.log("Persistent storage was granted.");
} else {
console.log("Persistent storage was not granted.");
}
return granted;
} catch (error) {
console.error("Unable to request persistent storage:", error);
return false;
}
}
The browser decides whether to grant the request. The result can depend on the browser's policies and how the user interacts with the application.
Some browsers may request user permission, while others may make the decision automatically.
Persistent storage helps protect an application's stored data from automatic browser eviction under storage pressure. It does not make storage unlimited, and it does not protect data from the user clearing site data through browser settings.
Therefore, this feature should be treated as an additional protection rather than a replacement for proper error handling.
For applications that store important offline work, requesting persistent storage can be useful. However, developers should still design the application so that it can recover when a storage operation fails.
Show Users How Much Storage They Are Using
Users should not have to discover storage problems only after an operation fails.
If an application allows users to download documents, images, videos, or other large resources, provide a storage section in the application settings.
The application can use navigator.storage.estimate() to show approximate storage usage.
async function getStorageInformation() {
if (!navigator.storage?.estimate) {
return null;
}
const estimate = await navigator.storage.estimate();
const usage = estimate.usage || 0;
const quota = estimate.quota || 0;
const percentage = quota > 0
? (usage / quota) * 100
: 0;
return {
usageMB: (usage / (1024 * 1024)).toFixed(2),
quotaMB: (quota / (1024 * 1024)).toFixed(2),
percentage: percentage.toFixed(1)
};
}
The application can display information such as:
Estimated storage usage: 420 MB
Estimated storage quota: 1 GB
Storage used: 42%
The wording should make it clear that these are estimates.
You can also provide controls that let users remove downloaded files, clear temporary content, or manage offline resources.
This is particularly useful in applications that store large files or support long periods of offline usage.
What Should Happen When Storage Is Completely Full?
The most important part of handling full browser storage is deciding what the application should do when a write operation fails.
Imagine a user editing a document while offline. The application tries to save the changes to IndexedDB, but the transaction fails because the browser has reached its quota.
The application should not display a successful save message.
Instead, it should explain that the changes could not be saved locally and provide a clear next step.
For example:
Unable to save your changes on this device.
Your browser storage is full. Remove some downloaded content
and try saving again.
The application should keep the edited content in memory while the current page remains open, where possible, so the user has an opportunity to copy or export it.
However, keeping data in memory is not a durable recovery strategy. If the user closes the tab or the browser crashes, that information may be lost.
For important workflows, consider providing an export option or allowing the user to download a local copy of the data.
If the application has a backend connection, it may also offer to save the changes directly to the server. This should happen only after the server confirms success.
The recovery process should be different for different types of data. A failed image cache operation may not need to interrupt the application, while a failed save operation for an offline document requires immediate attention.
Test Storage Failure Before Releasing the Application
Developers often test offline functionality by disconnecting the network. However, this does not test what happens when browser storage is full.
Storage failures need their own test cases.
One useful option is to use browser developer tools to simulate a smaller storage quota where the browser provides that capability.
For example, Chrome DevTools provides storage inspection and quota simulation tools. This allows developers to test how an application behaves when it has very little storage available.
You should also test the following situations:
Saving a small record when storage is almost full.
Saving a large file that exceeds the available quota.
Writing multiple IndexedDB records in one transaction.
Adding a resource to Cache Storage when the quota is exceeded.
Removing old cache entries and trying the operation again.
Running the application after persistent storage is denied.
Using private browsing or a browser with restricted storage.
Closing and reopening the application while data is waiting to synchronize.
The most important test is whether the application protects user data when a storage operation fails.
A successful test is not simply one where the application avoids crashing. It should also make sure that users understand what happened and have a way to recover their work.
Common Mistakes to Avoid
Assuming storage is unlimited
A developer may test an application with a small amount of data and assume that browser storage will always be available.
This becomes a problem when users download large files or store offline content over several weeks.
Use storage estimates where useful, but always handle failed writes.
Deleting all cached data
Removing every cache may free space, but it can also prevent an offline application from loading.
Separate essential application files from temporary resources and remove only the data that can safely be downloaded again.
Removing unsynchronized records
An old record is not necessarily an unnecessary record.
A record that has not been synchronized with the backend may be the only copy of the user's work.
Never delete pending user changes just to free storage.
Depending only on storage estimates
The values returned by navigator.storage.estimate() are approximate. The browser may change the available quota between the time of the estimate and the next write operation.
Use the estimate for planning and user information, not as a guarantee.
Treating persistent storage as a complete solution
Persistent storage reduces the risk of automatic eviction, but it does not provide unlimited space or protect data from every form of deletion.
Continue handling quota errors even when persistent storage has been granted.
Best Practices for Production Web Applications
A production application should have a clear storage management strategy instead of handling storage failures separately in different components.
Use IndexedDB for structured offline data and Cache Storage for resources that need to be available through the service worker. Keep localStorage for small values rather than using it for large application data.
Before storing large files, check the approximate storage usage and provide useful information to the user. When a write operation fails, identify whether the problem is related to storage capacity or another error.
Keep important user changes separate from temporary data. Remove old cache entries and downloaded resources before considering the removal of user-created records.
For applications that depend heavily on offline access, request persistent storage when appropriate. Also provide an export or recovery option for important local data.
Finally, test storage failures as part of the normal release process. An application that works only when storage is available is not fully prepared for real-world usage.
Conclusion
Browser storage makes it possible to build applications that work offline, save user information locally, and load previously downloaded content. However, browser storage has limits, and applications must be prepared for situations where those limits are reached.
The StorageManager API helps developers understand approximate storage usage, while QuotaExceededError provides a way to identify failed storage operations. IndexedDB and Cache Storage errors should be handled carefully so the application does not report success when data was not saved.
The most important decision is knowing what can safely be removed. Temporary files and old cached resources can often be downloaded again, but unsynchronized user changes may be impossible to recover.
A reliable web application does more than save data when storage is available. It also protects user work, explains storage problems clearly, and provides a safe recovery path when the browser cannot store anything more.
Join the conversation! Your thoughts help the community grow.