User Agents

Web browsers and everyday web tech, explained

How to Clear Cache in JavaScript

· 4 min read · Cookies and Cache

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Clearing cache in JavaScript typically means removing stored data from browser mechanisms like the Cache API, localStorage, sessionStorage, or IndexedDB. Unlike server-side systems, JavaScript itself doesn’t maintain a persistent memory cache, but modern web apps use browser storage APIs to cache data for performance. Clearing this cache improves app behavior during development, resolves stale data issues, or frees memory. This guide covers methods to programmatically clear various types of cached data using JavaScript.

What You'll Need

  • A modern web browser (Chrome, Firefox, Safari, Edge)
  • Access to the browser’s developer tools (F12 or right-click > Inspect)
  • JavaScript code execution environment (web page or console)
  • Knowledge of which caching mechanism your app uses (e.g., Cache API, localStorage)

Step-by-Step

  1. Identify the cache type: Determine which caching mechanism is being used. Common ones include localStorage, sessionStorage, Cache API, and IndexedDB. Check your code for calls like localStorage.setItem(), caches.open(), or indexedDB.open().
  2. Open browser developer tools: Press F12 or right-click the page and select "Inspect" to open DevTools. Navigate to the "Application" or "Storage" tab (Chrome/Edge) or "Storage" (Firefox).
  3. Clear localStorage and sessionStorage: In JavaScript, run localStorage.clear() to remove all localStorage entries. Use sessionStorage.clear() for session-only data. These commands delete all key-value pairs in their respective storages.
  4. Delete specific localStorage items: If you only want to remove certain items, use localStorage.removeItem('keyName'). Replace 'keyName' with the actual key string.
  5. Access the Cache API: The Cache API stores network responses. List all caches with caches.keys().then(console.log) in the console to see available cache names.
  6. Delete a specific cache: Use caches.delete('cache-name') to remove a named cache. Replace 'cache-name' with the actual name from the previous step.
  7. Clear all Cache API entries: Run caches.keys().then(names => { names.forEach(name => caches.delete(name)); }) to delete all caches at once.
  8. Clear IndexedDB databases: IndexedDB requires more effort. Use indexedDB.deleteDatabase('db-name') for each database. You can list databases via the browser’s Application tab or by tracking them in your code.
  9. Force-refresh the page: After clearing caches, perform a hard reload (Ctrl+F5 or Cmd+Shift+R) to ensure no stale assets are loaded from browser memory.
  10. Verify clearance: Return to the Application tab and inspect each storage type to confirm data is gone. Re-run localStorage.getItem() or caches.keys() in the console to verify.

Common Mistakes

  • Confusing cache types: Developers often mix up localStorage with the Cache API. Remember: localStorage stores strings; Cache API stores HTTP responses.
  • Not specifying the correct cache name: Using caches.delete() with a typo in the cache name fails silently. Always verify names with caches.keys() first.
  • Clearing caches in production by accident: Running global clear commands in live environments can disrupt user experience. Wrap cache-clearing logic in debug flags or admin controls.
  • Forgetting IndexedDB: Some apps rely on IndexedDB for large data. Ignoring it leaves residual data even after clearing other caches.
  • Assuming cache clears on page reload: sessionStorage clears on tab close, but localStorage and Cache API persist. Manual intervention is required.

Tips

  • Use versioned cache names: Name caches like my-app-cache-v1 so you can increment the version and clear old ones during updates.
  • Log cache operations: Add console.log after each clear operation to confirm execution, especially in service workers.
  • Clear caches during development builds: Automate cache clearing in dev mode using build scripts or conditional logic.
  • Test on multiple browsers: Cache behavior can vary slightly between browsers. Always verify your clearing logic works across targets.
  • Use the browser’s UI when possible: The Application tab allows manual deletion of storage types, useful for quick testing without code changes.

Troubleshooting

If cache clearing doesn’t work, first verify you’re targeting the right storage mechanism. For example, if data persists after localStorage.clear(), the app might be repopulating it immediately on load. Pause script execution or disable JavaScript temporarily to test. If caches.delete() returns false, the cache name may be incorrect or the cache may be in use by a service worker. Wait until the worker is inactive or unregister it via navigator.serviceWorker.getRegistrations().then(regs => regs.forEach(r => r.unregister())). For IndexedDB, ensure no open connections exist before deletion—close them with db.close() in your code. If the console throws security errors, the page may be running in a restricted context (e.g., iframe with allow-storage-access-by-user-activation). Test on a top-level page. Finally, if cached assets still load, check the network tab: the browser may be using disk or memory cache outside JavaScript control. A hard reload bypasses these.

Frequently Asked Questions

Does clearing cache in JavaScript delete cookies?

No, JavaScript cache clearing does not affect cookies. Use document.cookie manipulation or browser settings to clear cookies.

Can I clear cache for another domain?

No. Due to the same-origin policy, JavaScript can only access storage mechanisms on the current domain.

Why doesn’t localStorage.clear() work?

It may appear not to work if the page immediately repopulates localStorage on load. Check after a full reload or disable scripts temporarily.

Is it safe to clear caches in production?

Only if intended. Clearing caches logs users out or resets preferences. Use cautiously and provide user confirmation when needed.

Does cache clearing free up browser memory immediately?

Mostly yes, but the browser may delay garbage collection. Memory release isn't always instant.

Can service workers interfere with cache clearing?

Yes. Active service workers may control cache access. Unregister them first if you can’t delete a cache.