Zero config PWA solution for Nuxt.js applications with service worker management, manifest generation, and meta tag optimization
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Workbox integration for service worker management, caching strategies, and offline functionality with comprehensive configuration options.
Main function that sets up Workbox service worker with custom configuration.
/**
* Configure and setup Workbox service worker
* @param nuxt - Nuxt instance
* @param pwa - PWA context containing workbox configuration
* @param moduleContainer - Nuxt module container for plugins
*/
async function workbox(nuxt: any, pwa: PWAContext, moduleContainer: any): Promise<void>;
/**
* Process and normalize Workbox options with intelligent defaults
* @param nuxt - Nuxt instance
* @param pwa - PWA context containing workbox configuration
* @returns Fully processed WorkboxOptions with all defaults applied
*/
function getOptions(nuxt: any, pwa: PWAContext): WorkboxOptions;
interface WorkboxOptions {
/** Enable in development mode */
dev: boolean;
/** Workbox version to use */
workboxVersion: string;
/** Workbox CDN URL */
workboxURL: string;
/** Additional scripts to import in service worker */
importScripts: string[];
/** Auto-register service worker */
autoRegister: boolean;
/** Enable service worker functionality */
enabled: boolean;
/** Cache name configuration */
cacheNames: Record<string, any>;
/** Workbox configuration object */
config: Record<string, any>;
/** Take control of all clients immediately */
clientsClaim: boolean;
/** Skip waiting for existing service workers */
skipWaiting: boolean;
/** Enable offline Google Analytics */
offlineAnalytics: boolean;
/** Custom workbox extensions */
workboxExtensions: string | string[];
/** Files to precache on installation */
preCaching: string[] | {url: string, revision: string}[];
/** Cache configuration options */
cacheOptions: CacheOptions;
/** Custom caching extensions */
cachingExtensions: string | string[];
/** Clean up outdated caches */
cleanupOutdatedCaches: boolean;
/** Enable offline page functionality */
offline: boolean;
/** Caching strategy for offline pages */
offlineStrategy: CachingStrategy;
/** Path to offline fallback page */
offlinePage: string;
/** Assets to cache for offline use */
offlineAssets: string[];
/** Runtime caching rules */
runtimeCaching: RuntimeCaching[];
/** Cache application assets */
cacheAssets: boolean;
/** Custom routing extensions */
routingExtensions: string | string[];
/** URL pattern for application assets */
assetsURLPattern: string;
/** URL pattern for application pages */
pagesURLPattern: string;
/** Service worker template file */
swTemplate: string;
/** Service worker URL */
swURL: string;
/** Service worker destination path */
swDest: string;
/** Service worker scope */
swScope: string;
/** Router base path */
routerBase: string;
/** Public path for assets */
publicPath: string;
}
interface CacheOptions {
/** Unique cache identifier */
cacheId: string;
/** Directory index file */
directoryIndex: string;
/** Cache revision for invalidation */
revision: string | undefined;
}
type CachingStrategy = 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate';Usage Example:
// nuxt.config.ts
export default {
pwa: {
workbox: {
enabled: true,
offline: true,
cacheAssets: true,
runtimeCaching: [
{
urlPattern: '/api/.*',
handler: 'NetworkFirst',
strategyOptions: {
cacheName: 'api-cache',
networkTimeoutSeconds: 10
}
}
],
offlinePage: '/offline.html'
}
}
}Defines caching strategies for different URL patterns and HTTP methods.
interface RuntimeCaching {
/** URL pattern to match (string or regex) */
urlPattern: string;
/** Caching strategy to use */
handler?: CachingStrategy;
/** HTTP method to match */
method?: HTTPMethod;
/** Strategy-specific options */
strategyOptions?: StrategyOptions;
/** Strategy plugins to apply */
strategyPlugins?: StrategyPlugin[];
}
type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
type StrategyOptions = {
/** Cache name for this strategy */
cacheName?: string;
/** Network timeout in seconds */
networkTimeoutSeconds?: number;
/** Cache expiration options */
plugins?: any[];
};Usage Examples:
// API caching with network-first strategy
{
urlPattern: '/api/.*',
handler: 'NetworkFirst',
strategyOptions: {
cacheName: 'api-cache',
networkTimeoutSeconds: 10
},
strategyPlugins: [
{
use: 'Expiration',
config: { maxEntries: 50, maxAgeSeconds: 300 }
}
]
}
// Static assets with cache-first strategy
{
urlPattern: '/images/.*',
handler: 'CacheFirst',
strategyOptions: {
cacheName: 'images-cache'
},
strategyPlugins: [
{
use: 'CacheableResponse',
config: { statuses: [0, 200] }
}
]
}The getOptions function performs comprehensive option normalization and applies intelligent defaults:
/**
* Option processing features:
* - Automatic route pattern generation from Nuxt configuration
* - Intelligent cache strategy selection based on environment
* - Plugin module mapping and validation
* - Precaching optimization with URL normalization
* - Cache ID generation with environment-aware naming
*/
interface OptionProcessing {
/** Auto-generated URL patterns */
assetsURLPattern?: string; // From publicPath if not specified
pagesURLPattern?: string; // From routerBase if not specified
/** Environment-aware defaults */
enabled?: boolean; // Disabled in dev unless explicitly enabled
debug?: boolean; // Auto-set based on dev mode
/** Cache strategy optimization */
cacheAssets?: boolean; // Adds runtime caching for _nuxt assets
offlinePage?: string; // Adds page to precaching and runtime caching
/** Plugin normalization */
strategyPlugins: Array<{
use: string; // Mapped to full Workbox module path
config: any[]; // Normalized to array format
}>;
}Processing Logic:
URL Pattern Auto-generation:
assetsURLPattern defaults to publicPath for Nuxt asset cachingpagesURLPattern defaults to routerBase for page cachingCache Strategy Selection:
NetworkFirst for cache invalidationCacheFirst for performance optimizationPlugin Module Mapping:
const pluginModules = {
BackgroundSync: 'backgroundSync.BackgroundSyncPlugin',
BroadcastUpdate: 'broadcastUpdate.BroadcastUpdatePlugin',
CacheableResponse: 'cacheableResponse.CacheableResponsePlugin',
Expiration: 'expiration.ExpirationPlugin',
RangeRequests: 'rangeRequests.RangeRequestsPlugin'
};Precaching Optimization:
start_url from manifest to precachingofflinePage and offlineAssetsWorkbox strategy plugins for enhanced caching behavior.
type StrategyPlugin = BackgroundSync | BroadcastUpdate | CacheableResponse | Expiration | RangeRequests;
interface BackgroundSync {
use: 'BackgroundSync';
config: {
/** Background sync queue name */
name: string;
/** Retry options */
options?: any;
};
}
interface BroadcastUpdate {
use: 'BroadcastUpdate';
config: {
/** Channel name for broadcast */
channelName?: string;
/** Options for broadcast update */
options?: any;
};
}
interface CacheableResponse {
use: 'CacheableResponse';
config: {
/** HTTP status codes to cache */
statuses: number[];
/** Headers that make response cacheable */
headers?: Record<string, string>;
};
}
interface Expiration {
use: 'Expiration';
config: {
/** Maximum number of entries in cache */
maxEntries?: number;
/** Maximum age of cache entries in seconds */
maxAgeSeconds?: number;
/** Purge on quota error */
purgeOnQuotaError?: boolean;
};
}
interface RangeRequests {
use: 'RangeRequests';
config: any;
}Configure files and URLs to be cached during service worker installation.
/**
* Precaching configuration
*/
interface PrecachingConfig {
/** URLs or objects to precache */
preCaching: string[] | PrecacheEntry[];
/** Start URL from manifest */
startUrl?: string;
/** Offline page URL */
offlinePage?: string;
/** Additional offline assets */
offlineAssets: string[];
}
interface PrecacheEntry {
/** URL to precache */
url: string;
/** Revision hash for cache invalidation */
revision: string;
}Usage Example:
// nuxt.config.ts
export default {
pwa: {
workbox: {
preCaching: [
'/',
'/about',
'/contact'
],
offlinePage: '/offline.html',
offlineAssets: [
'/offline-logo.png',
'/offline-styles.css'
]
}
}
}Customizable service worker templates for different scenarios.
/**
* Service worker template configuration
*/
interface ServiceWorkerTemplate {
/** Path to service worker template */
swTemplate: string;
/** Destination path for generated service worker */
swDest: string;
/** Service worker URL */
swURL: string;
/** Service worker scope */
swScope: string;
}Available templates:
templates/workbox/sw.js - Full functionalitytemplates/workbox/sw.unregister.js - Cleanup existing SWSupport for custom extensions to extend service worker functionality.
/**
* Extension configuration
*/
interface ExtensionConfig {
/** Custom workbox extensions */
workboxExtensions: string | string[];
/** Custom caching logic extensions */
cachingExtensions: string | string[];
/** Custom routing extensions */
routingExtensions: string | string[];
}Extensions are JavaScript files that get included in the service worker:
// Custom caching extension example
workbox.routing.registerRoute(
/\/api\/custom\/.*/,
new workbox.strategies.NetworkFirst({
cacheName: 'custom-api-cache'
})
);Automatic service worker registration with configurable options.
/**
* Service worker registration configuration
*/
interface AutoRegistrationConfig {
/** Enable automatic registration */
autoRegister: boolean;
/** Service worker enabled */
enabled: boolean;
/** Registration options */
registrationOptions?: {
/** Service worker scope */
scope?: string;
/** Update via cache mode */
updateViaCache?: 'imports' | 'all' | 'none';
};
}Generated registration code:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js', {
scope: '/'
});
}Advanced cache management and cleanup options.
/**
* Cache management configuration
*/
interface CacheManagementConfig {
/** Custom cache names */
cacheNames: {
/** Precache cache name */
precache?: string;
/** Runtime cache name */
runtime?: string;
/** Prefix for all cache names */
prefix?: string;
/** Suffix for all cache names */
suffix?: string;
};
/** Clean up outdated caches */
cleanupOutdatedCaches: boolean;
/** Cache options */
cacheOptions: CacheOptions;
}Special handling for development environment.
/**
* Development mode configuration
*/
interface DevelopmentConfig {
/** Enable in development */
dev: boolean;
/** Debug configuration */
config: {
/** Enable debug logging */
debug?: boolean;
};
}In development mode:
Google Analytics support for offline events.
/**
* Offline analytics configuration
*/
interface OfflineAnalyticsConfig {
/** Enable offline Google Analytics */
offlineAnalytics: boolean;
/** Analytics configuration */
analyticsConfig?: {
/** Tracking ID */
trackingId?: string;
/** Custom parameters */
[key: string]: any;
};
}When enabled, captures analytics events while offline and sends them when connectivity is restored.
Comprehensive default configuration for production-ready PWAs:
const defaults: WorkboxOptions = {
// General
workboxVersion: '5.1.4', // From workbox-cdn
workboxURL: undefined, // Auto-generated CDN URL
importScripts: [],
autoRegister: true,
enabled: undefined, // Auto-set based on environment
// Config
config: {},
clientsClaim: true,
skipWaiting: true,
offlineAnalytics: false,
workboxExtensions: [],
// Precache
preCaching: [],
cacheOptions: {
cacheId: undefined, // Auto-generated
directoryIndex: '/',
revision: undefined // Auto-generated
},
cachingExtensions: [],
cleanupOutdatedCaches: true,
// Offline
offline: true,
offlineStrategy: 'NetworkFirst',
offlinePage: null,
offlineAssets: [],
// Runtime Caching
runtimeCaching: [],
routingExtensions: [],
cacheAssets: true,
assetsURLPattern: undefined, // Auto-set to publicPath
pagesURLPattern: undefined, // Auto-set to routerBase
// Service Worker
swTemplate: undefined, // Auto-selected based on enabled state
swURL: undefined, // Auto-set to routerBase + 'sw.js'
swScope: undefined, // Auto-set to routerBase
swDest: undefined, // Auto-set to static/sw.js
// Paths
routerBase: undefined, // From Nuxt config
publicPath: undefined, // From Nuxt config
dev: undefined,
cacheNames: undefined
};Install with Tessl CLI
npx tessl i tessl/npm-nuxtjs--pwa