0
# Service Worker & Caching
1
2
Workbox integration for service worker management, caching strategies, and offline functionality with comprehensive configuration options.
3
4
## Capabilities
5
6
### Workbox Integration Function
7
8
Main function that sets up Workbox service worker with custom configuration.
9
10
```typescript { .api }
11
/**
12
* Configure and setup Workbox service worker
13
* @param nuxt - Nuxt instance
14
* @param pwa - PWA context containing workbox configuration
15
* @param moduleContainer - Nuxt module container for plugins
16
*/
17
async function workbox(nuxt: any, pwa: PWAContext, moduleContainer: any): Promise<void>;
18
19
/**
20
* Process and normalize Workbox options with intelligent defaults
21
* @param nuxt - Nuxt instance
22
* @param pwa - PWA context containing workbox configuration
23
* @returns Fully processed WorkboxOptions with all defaults applied
24
*/
25
function getOptions(nuxt: any, pwa: PWAContext): WorkboxOptions;
26
27
interface WorkboxOptions {
28
/** Enable in development mode */
29
dev: boolean;
30
/** Workbox version to use */
31
workboxVersion: string;
32
/** Workbox CDN URL */
33
workboxURL: string;
34
/** Additional scripts to import in service worker */
35
importScripts: string[];
36
/** Auto-register service worker */
37
autoRegister: boolean;
38
/** Enable service worker functionality */
39
enabled: boolean;
40
/** Cache name configuration */
41
cacheNames: Record<string, any>;
42
/** Workbox configuration object */
43
config: Record<string, any>;
44
/** Take control of all clients immediately */
45
clientsClaim: boolean;
46
/** Skip waiting for existing service workers */
47
skipWaiting: boolean;
48
/** Enable offline Google Analytics */
49
offlineAnalytics: boolean;
50
/** Custom workbox extensions */
51
workboxExtensions: string | string[];
52
/** Files to precache on installation */
53
preCaching: string[] | {url: string, revision: string}[];
54
/** Cache configuration options */
55
cacheOptions: CacheOptions;
56
/** Custom caching extensions */
57
cachingExtensions: string | string[];
58
/** Clean up outdated caches */
59
cleanupOutdatedCaches: boolean;
60
/** Enable offline page functionality */
61
offline: boolean;
62
/** Caching strategy for offline pages */
63
offlineStrategy: CachingStrategy;
64
/** Path to offline fallback page */
65
offlinePage: string;
66
/** Assets to cache for offline use */
67
offlineAssets: string[];
68
/** Runtime caching rules */
69
runtimeCaching: RuntimeCaching[];
70
/** Cache application assets */
71
cacheAssets: boolean;
72
/** Custom routing extensions */
73
routingExtensions: string | string[];
74
/** URL pattern for application assets */
75
assetsURLPattern: string;
76
/** URL pattern for application pages */
77
pagesURLPattern: string;
78
/** Service worker template file */
79
swTemplate: string;
80
/** Service worker URL */
81
swURL: string;
82
/** Service worker destination path */
83
swDest: string;
84
/** Service worker scope */
85
swScope: string;
86
/** Router base path */
87
routerBase: string;
88
/** Public path for assets */
89
publicPath: string;
90
}
91
92
interface CacheOptions {
93
/** Unique cache identifier */
94
cacheId: string;
95
/** Directory index file */
96
directoryIndex: string;
97
/** Cache revision for invalidation */
98
revision: string | undefined;
99
}
100
101
type CachingStrategy = 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate';
102
```
103
104
**Usage Example:**
105
106
```typescript
107
// nuxt.config.ts
108
export default {
109
pwa: {
110
workbox: {
111
enabled: true,
112
offline: true,
113
cacheAssets: true,
114
runtimeCaching: [
115
{
116
urlPattern: '/api/.*',
117
handler: 'NetworkFirst',
118
strategyOptions: {
119
cacheName: 'api-cache',
120
networkTimeoutSeconds: 10
121
}
122
}
123
],
124
offlinePage: '/offline.html'
125
}
126
}
127
}
128
```
129
130
### Runtime Caching Configuration
131
132
Defines caching strategies for different URL patterns and HTTP methods.
133
134
```typescript { .api }
135
interface RuntimeCaching {
136
/** URL pattern to match (string or regex) */
137
urlPattern: string;
138
/** Caching strategy to use */
139
handler?: CachingStrategy;
140
/** HTTP method to match */
141
method?: HTTPMethod;
142
/** Strategy-specific options */
143
strategyOptions?: StrategyOptions;
144
/** Strategy plugins to apply */
145
strategyPlugins?: StrategyPlugin[];
146
}
147
148
type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
149
150
type StrategyOptions = {
151
/** Cache name for this strategy */
152
cacheName?: string;
153
/** Network timeout in seconds */
154
networkTimeoutSeconds?: number;
155
/** Cache expiration options */
156
plugins?: any[];
157
};
158
```
159
160
**Usage Examples:**
161
162
```typescript
163
// API caching with network-first strategy
164
{
165
urlPattern: '/api/.*',
166
handler: 'NetworkFirst',
167
strategyOptions: {
168
cacheName: 'api-cache',
169
networkTimeoutSeconds: 10
170
},
171
strategyPlugins: [
172
{
173
use: 'Expiration',
174
config: { maxEntries: 50, maxAgeSeconds: 300 }
175
}
176
]
177
}
178
179
// Static assets with cache-first strategy
180
{
181
urlPattern: '/images/.*',
182
handler: 'CacheFirst',
183
strategyOptions: {
184
cacheName: 'images-cache'
185
},
186
strategyPlugins: [
187
{
188
use: 'CacheableResponse',
189
config: { statuses: [0, 200] }
190
}
191
]
192
}
193
```
194
195
### Option Processing & Defaults
196
197
The `getOptions` function performs comprehensive option normalization and applies intelligent defaults:
198
199
```typescript { .api }
200
/**
201
* Option processing features:
202
* - Automatic route pattern generation from Nuxt configuration
203
* - Intelligent cache strategy selection based on environment
204
* - Plugin module mapping and validation
205
* - Precaching optimization with URL normalization
206
* - Cache ID generation with environment-aware naming
207
*/
208
interface OptionProcessing {
209
/** Auto-generated URL patterns */
210
assetsURLPattern?: string; // From publicPath if not specified
211
pagesURLPattern?: string; // From routerBase if not specified
212
213
/** Environment-aware defaults */
214
enabled?: boolean; // Disabled in dev unless explicitly enabled
215
debug?: boolean; // Auto-set based on dev mode
216
217
/** Cache strategy optimization */
218
cacheAssets?: boolean; // Adds runtime caching for _nuxt assets
219
offlinePage?: string; // Adds page to precaching and runtime caching
220
221
/** Plugin normalization */
222
strategyPlugins: Array<{
223
use: string; // Mapped to full Workbox module path
224
config: any[]; // Normalized to array format
225
}>;
226
}
227
```
228
229
**Processing Logic:**
230
231
1. **URL Pattern Auto-generation:**
232
- `assetsURLPattern` defaults to `publicPath` for Nuxt asset caching
233
- `pagesURLPattern` defaults to `routerBase` for page caching
234
235
2. **Cache Strategy Selection:**
236
- Development: Prefers `NetworkFirst` for cache invalidation
237
- Production: Uses `CacheFirst` for performance optimization
238
239
3. **Plugin Module Mapping:**
240
```typescript
241
const pluginModules = {
242
BackgroundSync: 'backgroundSync.BackgroundSyncPlugin',
243
BroadcastUpdate: 'broadcastUpdate.BroadcastUpdatePlugin',
244
CacheableResponse: 'cacheableResponse.CacheableResponsePlugin',
245
Expiration: 'expiration.ExpirationPlugin',
246
RangeRequests: 'rangeRequests.RangeRequestsPlugin'
247
};
248
```
249
250
4. **Precaching Optimization:**
251
- Adds `start_url` from manifest to precaching
252
- Includes `offlinePage` and `offlineAssets`
253
- Normalizes all entries with revision hashes
254
255
### Strategy Plugins
256
257
Workbox strategy plugins for enhanced caching behavior.
258
259
```typescript { .api }
260
type StrategyPlugin = BackgroundSync | BroadcastUpdate | CacheableResponse | Expiration | RangeRequests;
261
262
interface BackgroundSync {
263
use: 'BackgroundSync';
264
config: {
265
/** Background sync queue name */
266
name: string;
267
/** Retry options */
268
options?: any;
269
};
270
}
271
272
interface BroadcastUpdate {
273
use: 'BroadcastUpdate';
274
config: {
275
/** Channel name for broadcast */
276
channelName?: string;
277
/** Options for broadcast update */
278
options?: any;
279
};
280
}
281
282
interface CacheableResponse {
283
use: 'CacheableResponse';
284
config: {
285
/** HTTP status codes to cache */
286
statuses: number[];
287
/** Headers that make response cacheable */
288
headers?: Record<string, string>;
289
};
290
}
291
292
interface Expiration {
293
use: 'Expiration';
294
config: {
295
/** Maximum number of entries in cache */
296
maxEntries?: number;
297
/** Maximum age of cache entries in seconds */
298
maxAgeSeconds?: number;
299
/** Purge on quota error */
300
purgeOnQuotaError?: boolean;
301
};
302
}
303
304
interface RangeRequests {
305
use: 'RangeRequests';
306
config: any;
307
}
308
```
309
310
### Precaching Configuration
311
312
Configure files and URLs to be cached during service worker installation.
313
314
```typescript { .api }
315
/**
316
* Precaching configuration
317
*/
318
interface PrecachingConfig {
319
/** URLs or objects to precache */
320
preCaching: string[] | PrecacheEntry[];
321
/** Start URL from manifest */
322
startUrl?: string;
323
/** Offline page URL */
324
offlinePage?: string;
325
/** Additional offline assets */
326
offlineAssets: string[];
327
}
328
329
interface PrecacheEntry {
330
/** URL to precache */
331
url: string;
332
/** Revision hash for cache invalidation */
333
revision: string;
334
}
335
```
336
337
**Usage Example:**
338
339
```typescript
340
// nuxt.config.ts
341
export default {
342
pwa: {
343
workbox: {
344
preCaching: [
345
'/',
346
'/about',
347
'/contact'
348
],
349
offlinePage: '/offline.html',
350
offlineAssets: [
351
'/offline-logo.png',
352
'/offline-styles.css'
353
]
354
}
355
}
356
}
357
```
358
359
### Service Worker Templates
360
361
Customizable service worker templates for different scenarios.
362
363
```typescript { .api }
364
/**
365
* Service worker template configuration
366
*/
367
interface ServiceWorkerTemplate {
368
/** Path to service worker template */
369
swTemplate: string;
370
/** Destination path for generated service worker */
371
swDest: string;
372
/** Service worker URL */
373
swURL: string;
374
/** Service worker scope */
375
swScope: string;
376
}
377
```
378
379
Available templates:
380
- **Active SW**: `templates/workbox/sw.js` - Full functionality
381
- **Unregister SW**: `templates/workbox/sw.unregister.js` - Cleanup existing SW
382
383
### Extension System
384
385
Support for custom extensions to extend service worker functionality.
386
387
```typescript { .api }
388
/**
389
* Extension configuration
390
*/
391
interface ExtensionConfig {
392
/** Custom workbox extensions */
393
workboxExtensions: string | string[];
394
/** Custom caching logic extensions */
395
cachingExtensions: string | string[];
396
/** Custom routing extensions */
397
routingExtensions: string | string[];
398
}
399
```
400
401
Extensions are JavaScript files that get included in the service worker:
402
```javascript
403
// Custom caching extension example
404
workbox.routing.registerRoute(
405
/\/api\/custom\/.*/,
406
new workbox.strategies.NetworkFirst({
407
cacheName: 'custom-api-cache'
408
})
409
);
410
```
411
412
### Auto-Registration
413
414
Automatic service worker registration with configurable options.
415
416
```typescript { .api }
417
/**
418
* Service worker registration configuration
419
*/
420
interface AutoRegistrationConfig {
421
/** Enable automatic registration */
422
autoRegister: boolean;
423
/** Service worker enabled */
424
enabled: boolean;
425
/** Registration options */
426
registrationOptions?: {
427
/** Service worker scope */
428
scope?: string;
429
/** Update via cache mode */
430
updateViaCache?: 'imports' | 'all' | 'none';
431
};
432
}
433
```
434
435
Generated registration code:
436
```javascript
437
if ('serviceWorker' in navigator) {
438
navigator.serviceWorker.register('/sw.js', {
439
scope: '/'
440
});
441
}
442
```
443
444
### Cache Management
445
446
Advanced cache management and cleanup options.
447
448
```typescript { .api }
449
/**
450
* Cache management configuration
451
*/
452
interface CacheManagementConfig {
453
/** Custom cache names */
454
cacheNames: {
455
/** Precache cache name */
456
precache?: string;
457
/** Runtime cache name */
458
runtime?: string;
459
/** Prefix for all cache names */
460
prefix?: string;
461
/** Suffix for all cache names */
462
suffix?: string;
463
};
464
/** Clean up outdated caches */
465
cleanupOutdatedCaches: boolean;
466
/** Cache options */
467
cacheOptions: CacheOptions;
468
}
469
```
470
471
### Development Mode
472
473
Special handling for development environment.
474
475
```typescript { .api }
476
/**
477
* Development mode configuration
478
*/
479
interface DevelopmentConfig {
480
/** Enable in development */
481
dev: boolean;
482
/** Debug configuration */
483
config: {
484
/** Enable debug logging */
485
debug?: boolean;
486
};
487
}
488
```
489
490
In development mode:
491
- Service worker shows debug information
492
- Network-first strategies are preferred
493
- Cache invalidation is more aggressive
494
- Warning messages are displayed for configuration issues
495
496
### Offline Analytics
497
498
Google Analytics support for offline events.
499
500
```typescript { .api }
501
/**
502
* Offline analytics configuration
503
*/
504
interface OfflineAnalyticsConfig {
505
/** Enable offline Google Analytics */
506
offlineAnalytics: boolean;
507
/** Analytics configuration */
508
analyticsConfig?: {
509
/** Tracking ID */
510
trackingId?: string;
511
/** Custom parameters */
512
[key: string]: any;
513
};
514
}
515
```
516
517
When enabled, captures analytics events while offline and sends them when connectivity is restored.
518
519
### Default Configuration
520
521
Comprehensive default configuration for production-ready PWAs:
522
523
```typescript { .api }
524
const defaults: WorkboxOptions = {
525
// General
526
workboxVersion: '5.1.4', // From workbox-cdn
527
workboxURL: undefined, // Auto-generated CDN URL
528
importScripts: [],
529
autoRegister: true,
530
enabled: undefined, // Auto-set based on environment
531
532
// Config
533
config: {},
534
clientsClaim: true,
535
skipWaiting: true,
536
offlineAnalytics: false,
537
workboxExtensions: [],
538
539
// Precache
540
preCaching: [],
541
cacheOptions: {
542
cacheId: undefined, // Auto-generated
543
directoryIndex: '/',
544
revision: undefined // Auto-generated
545
},
546
cachingExtensions: [],
547
cleanupOutdatedCaches: true,
548
549
// Offline
550
offline: true,
551
offlineStrategy: 'NetworkFirst',
552
offlinePage: null,
553
offlineAssets: [],
554
555
// Runtime Caching
556
runtimeCaching: [],
557
routingExtensions: [],
558
cacheAssets: true,
559
assetsURLPattern: undefined, // Auto-set to publicPath
560
pagesURLPattern: undefined, // Auto-set to routerBase
561
562
// Service Worker
563
swTemplate: undefined, // Auto-selected based on enabled state
564
swURL: undefined, // Auto-set to routerBase + 'sw.js'
565
swScope: undefined, // Auto-set to routerBase
566
swDest: undefined, // Auto-set to static/sw.js
567
568
// Paths
569
routerBase: undefined, // From Nuxt config
570
publicPath: undefined, // From Nuxt config
571
572
dev: undefined,
573
cacheNames: undefined
574
};
575
```