To clean up stale or expired data (TTL: Time-To-Live) periodically in
IndexedDB, you need to manually implement a cleanup strategy since IndexedDB has
no built-in TTL or expiration mechanism.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Here’s a complete approach:
Strategy to Clean Stale/Expired Data in IndexedDB
1. Store Timestamps with Your Data
Include an
updatedAtorexpiresAtfield (timestamp) in each record:2. Periodic Cleanup Function
You can create a scheduled cleanup function that deletes expired records.
Or if using
expiresAt:3. Schedule Cleanup Periodically
There are a few ways to trigger cleanup:
On App Start:
With
setInterval:On Tab Visibility Change:
4. Optional: Use an Index for
expiresAt(Performance Boost)When defining your IndexedDB schema (e.g., with Dexie.js):
Then you can query efficiently with:
5. Add Guard on Read (to prevent use of expired records)
Example with Dexie.js
Summary
updatedAtorexpiresAtwhere(...).below(...).delete()setInterval,visibilitychange, or on startup