# Auto Clear Cache

A lightweight, reliable utility to automatically detect new deployments, clear browser caches, and reload your web app — ensuring users always experience the latest build.

[![GitHub](https://img.shields.io/badge/GitHub-auto--clear--cache-blue?style=flat&logo=github)](https://github.com/keroloszakaria/auto-clear-cache)
[![License](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
[![npm](https://img.shields.io/npm/v/auto-clear-cache?color=cb3837&logo=npm)](https://www.npmjs.com/package/auto-clear-cache)
[![Vite](https://img.shields.io/badge/Vite-Plugin-646CFF?style=flat&logo=vite)](https://vitejs.dev/)
[![JavaScript](https://img.shields.io/badge/JavaScript-ESM-F7DF1E?logo=javascript)](https://developer.mozilla.org/en-US/docs/Web/JavaScript)

> 📦 **Package**: [npm](https://www.npmjs.com/package/auto-clear-cache)  
> 📚 **Source**: [GitHub](https://github.com/keroloszakaria/auto-clear-cache)

---

## Features

- ✅ Detects new versions **and new deployments** via `version.json`
- 🧹 Clears browser data: Cache, LocalStorage, SessionStorage, Cookies, IndexedDB, and Service Workers
- 🔁 Optional clear on **every deploy** using `buildId`
- ⏱️ Optional **periodic cache cleanup** (e.g. every 12h / 24h)
- ⚙️ Fully configurable with lifecycle callbacks
- 💡 Works with **Vite**, **Vue**, **Nuxt**, **React**, **Next.js**, **Angular**, **Svelte**, and plain JavaScript
- 🚀 Includes a Vite plugin for automatic version/build generation
- 🧱 Safe for SSR, PWA, and offline-aware apps
- 📦 Ships as **built & minified dist only** on npm

---

## Installation

```bash
npm install auto-clear-cache
# or
yarn add auto-clear-cache
# or
pnpm add auto-clear-cache
```

---

## Quick Start

### 1️⃣ Add Vite Plugin

```ts
// vite.config.ts
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { versionPlugin } from "auto-clear-cache";

export default defineConfig({
  plugins: [vue(), versionPlugin()],
});
```

This generates a `version.json` file on every build.

---

### 2️⃣ Use in App Entry

```ts
// main.ts
import autoClearCache from "auto-clear-cache";

autoClearCache({
  askUserBeforeReload: true,
});
```

Default behavior:

- Fetches `version.json`
- Clears all browser caches on change
- Reloads the app

---

## Framework Integrations

### Vue 3

```ts
import { createApp } from "vue";
import App from "./App.vue";
import autoClearCache from "auto-clear-cache";

autoClearCache({
  onVersionChange: (oldV, newV) => console.log(`Updating ${oldV} → ${newV}`),
});

createApp(App).mount("#app");
```

---

### Nuxt 3

```ts
// plugins/version-check.client.ts
import { defineNuxtPlugin } from "#app";
import autoClearCache from "auto-clear-cache";

export default defineNuxtPlugin(() => {
  autoClearCache({
    path: "/version.json",
    askUserBeforeReload: true,
  });
});
```

> Must use `.client.ts`.

---

### React (Vite)

```tsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import autoClearCache from "auto-clear-cache";

autoClearCache().then(() => {
  ReactDOM.createRoot(document.getElementById("root")!).render(<App />);
});
```

---

### Next.js (App Router)

```tsx
"use client";
import { useEffect } from "react";
import autoClearCache from "auto-clear-cache";

export default function VersionChecker() {
  useEffect(() => {
    autoClearCache({
      path: "/version.json",
      askUserBeforeReload: true,
    });
  }, []);

  return null;
}
```

---

### Vanilla JS

```html
<script type="module">
  import autoClearCache from "auto-clear-cache";
  autoClearCache();
</script>
```

---

## Configuration

### autoClearCache / checkVersionAndReload

| Option              | Type     | Default         | Description                |
| ------------------- | -------- | --------------- | -------------------------- |
| path                | string   | `/version.json` | Version file path          |
| localStorageKey     | string   | `app_version`   | Stored version key         |
| clearEverything     | boolean  | `true`          | Clear all browser data     |
| forceClearOnBuild   | boolean  | `false`         | Clear on every deploy      |
| clearIntervalMs     | number   | `null`          | Periodic clearing interval |
| delayBeforeReload   | number   | `0`             | Reload delay (ms)          |
| askUserBeforeReload | boolean  | `false`         | Confirm before reload      |
| verbose             | boolean  | `true`          | Enable logs                |
| onVersionChange     | function | —               | When version/build changes |
| onVersionMatch      | function | —               | When version matches       |
| onError             | function | —               | On error                   |

---

### clearAllBrowserData

| Option                | Type     | Default | Description                |
| --------------------- | -------- | ------- | -------------------------- |
| `clearLocalStorage`   | boolean  | `true`  | Clear LocalStorage         |
| `clearSessionStorage` | boolean  | `true`  | Clear SessionStorage       |
| `clearCacheStorage`   | boolean  | `true`  | Clear CacheStorage         |
| `clearCookies`        | boolean  | `true`  | Clear Cookies              |
| `clearIndexedDB`      | boolean  | `true`  | Clear IndexedDB            |
| `clearServiceWorkers` | boolean  | `true`  | Unregister Service Workers |
| `excludeLocalStorage` | string[] | `[]`    | Keys to preserve           |
| `excludeCookies`      | string[] | `[]`    | Cookies to preserve        |

---

## Advanced Examples

### Clear on Every Deploy

```ts
autoClearCache({
  forceClearOnBuild: true,
});
```

### Periodic Cleanup (24h)

```ts
autoClearCache({
  clearIntervalMs: 24 * 60 * 60 * 1000,
});
```

### Preserve Auth Data

```ts
autoClearCache({
  onVersionChange: async () => {
    await clearAllBrowserData({
      excludeLocalStorage: ["auth_token"],
      excludeCookies: ["session_id"],
    });
  },
});
```

---

## Changelog

See full changelog → [CHANGELOG.md](./CHANGELOG.md)

### v1.3.0

- Default export support (`autoClearCache()`)
- Clear cache on every deploy using `forceClearOnBuild`
- Periodic cache cleanup via `clearIntervalMs`
- Added `buildId` to `version.json`
- Library build & obfuscated `dist` output
- Improved SSR and offline safety
- Documentation overhaul with advanced guides

### v1.2.0

- Added Nuxt 3 and Next.js integrations
- Introduced lifecycle callbacks and exclusions
- Added `delayBeforeReload` and `askUserBeforeReload`
- Improved Service Worker and IndexedDB cleanup
- Enhanced console output and verbose logging

---

## Author

**Kerolos Zakaria**  
[Portfolio](https://keroloszakaria.surge.sh) • [GitHub](https://github.com/keroloszakaria) • [VS Code Marketplace](https://marketplace.visualstudio.com/publishers/keroloszakaria) • [npm](https://www.npmjs.com/settings/keroloszakaria/packages) • [LinkedIn](https://linkedin.com/in/keroloszakaria)

---

## License

MIT © 2025 Kerolos Zakaria
