0
# Plugin-Based Expiration
1
2
Workbox plugin for seamless integration with caching strategies, providing automatic expiration based on age and entry limits during cache operations.
3
4
## Capabilities
5
6
### ExpirationPlugin Class
7
8
Workbox plugin that automatically handles expiration during cache operations.
9
10
```typescript { .api }
11
/**
12
* Plugin for workbox-strategy to regularly enforce limits on age and/or number of cached requests.
13
* Can only be used with workbox-strategy instances that have a custom cacheName property set.
14
* Cannot be used to expire entries in strategies that use the default runtime cache name.
15
*/
16
class ExpirationPlugin {
17
/**
18
* Constructs a new ExpirationPlugin. At least one of maxEntries or maxAgeSeconds must be provided.
19
* @param config - Plugin configuration options
20
*/
21
constructor(config: ExpirationPluginOptions = {});
22
23
/**
24
* Deletes all underlying Cache instances associated with this plugin and
25
* removes metadata from IndexedDB. Preferable to calling caches.delete() directly
26
* when using cache expiration as it ensures IndexedDB cleanup.
27
*/
28
deleteCacheAndMetadata(): Promise<void>;
29
30
// Plugin lifecycle methods (automatically called by Workbox strategies)
31
cachedResponseWillBeUsed?: WorkboxPlugin['cachedResponseWillBeUsed'];
32
cacheDidUpdate?: WorkboxPlugin['cacheDidUpdate'];
33
}
34
35
interface ExpirationPluginOptions {
36
/** Maximum number of entries to cache. Entries used least recently will be removed first. */
37
maxEntries?: number;
38
/** Maximum age of an entry in seconds before it's treated as stale and removed. */
39
maxAgeSeconds?: number;
40
/** CacheQueryOptions that will be used when calling delete() on the cache. */
41
matchOptions?: CacheQueryOptions;
42
/** Whether to opt this cache into automatic deletion if available storage quota has been exceeded. */
43
purgeOnQuotaError?: boolean;
44
}
45
```
46
47
**Usage Examples:**
48
49
```typescript
50
import { ExpirationPlugin } from "workbox-expiration";
51
import { StaleWhileRevalidate, CacheFirst } from "workbox-strategies";
52
53
// Basic usage with a caching strategy
54
const strategy = new StaleWhileRevalidate({
55
cacheName: "api-cache",
56
plugins: [
57
new ExpirationPlugin({
58
maxEntries: 50,
59
maxAgeSeconds: 60 * 60 * 24, // 24 hours
60
}),
61
],
62
});
63
64
// With automatic quota error cleanup
65
const limitedStrategy = new CacheFirst({
66
cacheName: "images",
67
plugins: [
68
new ExpirationPlugin({
69
maxEntries: 100,
70
maxAgeSeconds: 60 * 60 * 24 * 30, // 30 days
71
purgeOnQuotaError: true,
72
}),
73
],
74
});
75
76
// Custom cache query options
77
const customStrategy = new StaleWhileRevalidate({
78
cacheName: "custom-cache",
79
plugins: [
80
new ExpirationPlugin({
81
maxEntries: 25,
82
matchOptions: {
83
ignoreSearch: true,
84
ignoreVary: true,
85
},
86
}),
87
],
88
});
89
90
// Manual cleanup of all caches managed by plugin
91
const plugin = new ExpirationPlugin({
92
maxEntries: 50,
93
maxAgeSeconds: 60 * 60,
94
});
95
96
// Later, when needed
97
await plugin.deleteCacheAndMetadata();
98
```
99
100
### Plugin Lifecycle Behavior
101
102
The plugin automatically integrates with Workbox strategy lifecycle:
103
104
**cachedResponseWillBeUsed:**
105
- Triggered when a cached response is about to be returned
106
- Checks response freshness using HTTP Date header if `maxAgeSeconds` is configured
107
- Returns `null` for expired responses (causing strategy to fetch fresh)
108
- Updates entry timestamp and triggers background expiration
109
110
**cacheDidUpdate:**
111
- Triggered when an entry is added or updated in the cache
112
- Updates the entry's timestamp for accurate LRU tracking
113
- Runs expiration process to remove old/excess entries
114
115
### Error Conditions
116
117
**Constructor Errors:**
118
- Throws `WorkboxError` with code `max-entries-or-age-required` if neither `maxEntries` nor `maxAgeSeconds` is provided
119
120
**Runtime Errors:**
121
- Throws `WorkboxError` with code `expire-custom-caches-only` if used with the default runtime cache name
122
123
### Implementation Details
124
125
- Automatically manages `CacheExpiration` instances for each cache
126
- Integrates with `registerQuotaErrorCallback` when `purgeOnQuotaError` is enabled
127
- Performs lightweight HTTP Date header validation before IndexedDB checks
128
- Uses `dontWaitFor` pattern to avoid blocking cache operations during expiration
129
- Handles service worker event lifecycle with `event.waitUntil()` when available
130
131
### Quota Error Handling
132
133
When `purgeOnQuotaError` is enabled:
134
- Registers a callback with Workbox core quota error handling
135
- Automatically calls `deleteCacheAndMetadata()` when storage quota is exceeded
136
- Helps prevent persistent quota exceeded errors by cleaning up expired data