29 KiB
PWA lib (packages/libs/src/pwa)
Makes each app an installable PWA whose repeat visits load JS, CSS, fonts, and the icon sprite from the device. Each app serves one service worker, built from this lib, and the worker stores exactly four kinds of files: JS and CSS from /_next/static/, fonts from /fonts/, and /icons/symbol-defs.svg. Every other request, pages and data included, reaches the network as if no worker existed. Framework-agnostic; built on the native Service Worker and Cache APIs; no dependency (no Workbox or Serwist).
It isn't an offline app. Every page renders fresh on the server for each request (b2c-b2b.md), so a visitor without a connection sees the browser's offline page.
Contents: What the worker stores · Structure · Types · API · The worker · Updates and the kill switch · Serving the worker · Measuring · Web app manifest · Not in this lib · Implementation · Usage · Acceptance checklist
What the worker stores
| Kind | URL | Why a stored copy stays correct |
|---|---|---|
| JS | /_next/static/**/*.js |
Next.js puts a content hash in every name, so a URL never changes content |
| CSS | /_next/static/**/*.css |
The same content hash |
| Fonts | /fonts/*.woff2 |
A font never changes under its name; a changed font ships under a new name (ui-rules.md) |
| Icon sprite | /icons/symbol-defs.svg?v=<N> |
Every change raises ICON_SPRITE_VERSION, so the URL changes with the content |
- Same origin and
GETonly. A response is stored only when it has status 200, came from the same origin (typeis'basic'), and wasn't redirected. Never a partial (206), opaque, redirected, or error response. - Stale-while-revalidate, by the exact URL with its query string, is the default: a stored file is served at once, and a background request checks it. When that response has a different
ETag(or, without one, a differentLast-Modified), it replaces the stored copy; an unchanged file is never written again. A miss goes to the network, and the response is stored for the next request. - Cache first only when the developer explicitly asks for it, with
writeServiceWorker({ strategy: 'cache-first' })in the app'snext.config.ts. A stored file is then served with no network request at all. Write the choice and its reason in the plan, and record it as a decision when it's lasting (decisions.md). - The trade-off: these files are immutable under their URLs, so the HTTP cache answers almost every background check, but a visitor whose HTTP cache dropped the file downloads it again. In return, a file that changed under its URL against the rules, such as a font changed under its old name, heals after one visit. Cache first saves those checks and never notices such a change.
symbol-defs.svgis the only SVG the worker stores. Every other SVG, such as a logo, an illustration,/_next/static/media/*.svg, or an image on the CDN, is an image, and the worker leaves images alone.- Storing a new sprite version deletes the older ones, so the cache holds one sprite.
- Everything sits in one cache,
pwa-assets-v1. Above 200 entries, the oldest go first. An evicted file costs one request, usually answered by the HTTP cache. - The cache holds only public files that are the same for every visitor, so logout and shared devices need nothing from this lib.
- Storing any other kind of URL changes the architecture. Record it as a decision first (decisions.md).
Structure
packages/libs/src/pwa/
├── pwa.ts # configureServiceWorker and registerServiceWorker: the page side
├── service-worker.ts # the worker: a classic script that writeServiceWorker compiles into public/sw.js
├── service-worker-plugin.ts # writeServiceWorker: the build and dev plugin
├── types.ts # ServiceWorkerOptions, ServiceWorkerConfig, CacheStrategy, CacheLoadedMessage, ServiceWorkerPluginOptions
├── constants.ts # SERVICE_WORKER_URL, SERVICE_WORKER_SCOPE, CACHE_NAME_PREFIX, SERVICE_WORKER_CONFIG, SERVICE_WORKER_HEADERS
├── index.ts # the page side
└── plugin.ts # the build side; imported only from build configs
index.tsexportsconfigureServiceWorker,registerServiceWorker,SERVICE_WORKER_URL,SERVICE_WORKER_CONFIG, and the typesServiceWorkerOptionsandServiceWorkerConfig. It runs nothing at import, sobootstrap.client.tscan import it during SSR. Nothing goes inserver.ts.plugin.tsexportswriteServiceWorker,SERVICE_WORKER_URL,SERVICE_WORKER_HEADERS, and the typesServiceWorkerPluginOptionsandCacheStrategy, on the@project/libs/pwa/pluginsubpath. It runs in Node, because it reads and writes files. Only build configs import it, never app code, and no root entry re-exports it. A client import fails the build, because the browser has nonode:fs.service-worker.tsruns in the worker's own global scope. It has noimportorexport, so the plugin can emit it as one script, and it reads its settings fromSERVICE_WORKER_CONFIG, which the plugin writes above it.packages/libs/tsconfig.worker.jsontype-checks it withlib: ["ES2022", "WebWorker"]. The lib's main tsconfig excludes it, so worker globals such asclientsnever reach the page code's types: theDOMandWebWorkerlibs declare the same globals differently.- Import by subpath:
import { registerServiceWorker } from '@project/libs/pwa', and innext.config.ts,import { writeServiceWorker } from '@project/libs/pwa/plugin'.
Types
type ServiceWorkerOptions = {
enabled: boolean; // from the app's env; false unregisters the worker and deletes its caches
};
type CacheStrategy = 'stale-while-revalidate' | 'cache-first';
// The worker's settings. writeServiceWorker writes them into public/sw.js; the worker reads nothing else.
type ServiceWorkerConfig = {
strategy: CacheStrategy; // 'stale-while-revalidate' unless the developer explicitly chose 'cache-first'
cacheName: string; // the one cache, e.g. 'pwa-assets-v1'
cachePrefix: string; // every cache this lib owns starts with it
maxEntries: number; // above it, the oldest entries go first
cacheLoadedMessage: string; // the type of the message that lists what the page already loaded
paths: {
static: string; // '/_next/static/': .js and .css only
fonts: string; // '/fonts/': .woff2 only
sprite: string; // '/icons/symbol-defs.svg', stored with its ?v=<N>
};
};
// The page lists what it loaded before the worker controlled it.
type CacheLoadedMessage = {
type: string;
urls: string[];
};
type ServiceWorkerPluginOptions = {
publicDir: string; // absolute path of the app's public/
strategy?: CacheStrategy; // only when the developer explicitly changes it; default 'stale-while-revalidate'
};
API
configureServiceWorker(options)runs once, inbootstrap.client.ts, withenabledfrom the app's env. It only stores options, so it's safe during SSR. Until it runs,enabledisfalse.registerServiceWorker()runs once per page load, in an effect of the platform'sAppShell. It returns at once and does its work in the background:- With
enabled: true, it waits for the window'sloadevent, so the worker never competes with the page for the network. Then it registers/sw.jswith scope/andupdateViaCache: 'none'. When the worker didn't control this page load yet (a first visit, or a hard reload), it sends the worker the URLs the page has already loaded (performance.getEntriesByType('resource')), so the worker stores the matching files from the HTTP cache at once. - With
enabled: false, it unregisters every worker of the origin and deletes every cache whose name starts withpwa-. That's the kill switch. - Browsers without service workers, and plain-
httphosts other thanlocalhost, skip it. A failed registration is ignored: the worker only makes repeat visits faster, and the site works the same without it. - On the server, it throws a clear error ("registerServiceWorker is browser-only; call it in an effect") instead of the unclear "window is not defined".
- With
writeServiceWorker({ publicDir, strategy })compilesservice-worker.tswith the workspace's owntypescript(transpileModule; no new dependency), writesSERVICE_WORKER_CONFIGabove it with the developer'sstrategywhen one is passed, and saves the result as<publicDir>/sw.js. It writes only when the content changed, so the dev server's file watchers don't restart for nothing.sw.jsis generated, so git ignores it, like the fonts and the sprite inpublic/.- Add
{projectRoot}/public/sw.jsto the app's build targetoutputs, so an Nx cache hit restores it together with.next/. A deploy without it serves a 404 at/sw.js.
The worker
install: callsskipWaiting(). On Chromium (Chrome 123 and later, Static Routing API) it also adds one route that sends navigations straight to the network, so the worker never starts only to let a page through.activate: turns on navigation preload, deletes everypwa-cache except the current one, and callsclients.claim(), so the open pages use the new worker at once.fetch:- Non-
GETrequests: untouched. - Navigations, on browsers without static routing: answered with the navigation preload response, so the page request starts while the worker starts (Chrome 59, Edge 18, Firefox 99, and Safari 15.4 and later), or with
fetchwhen preload is off. Never stored. - The four kinds in the table: stale-while-revalidate, or cache first when the developer chose it.
- Everything else (RSC payloads, API calls, images, media, other SVGs, and cross-origin requests): no
respondWith, so the browser handles it as if no worker existed. - An
only-if-cachedrequest whose mode isn'tsame-origin(DevTools sends them) is left alone, becausefetchrejects it.
- Non-
message: the page's list of loaded URLs. The worker checks each URL against the four kinds again, because it trusts no message, and stores the ones it doesn't have.- The worker runs only this lib's code: no
importScripts, no third-party code, and no push, sync, or other events.
Updates and the kill switch
sw.jschanges only when this lib changes (its worker code orSERVICE_WORKER_CONFIG). The deploy that ships the change reaches each visitor at their next navigation: the browser checks/sw.js, installs the new worker, and the new worker takes over at once.- Taking over at once is safe because the worker never stores pages. Every page already comes from the current deploy, and every stored file is immutable under its URL. So there is no "new version available" prompt.
- Raise the
v1inSERVICE_WORKER_CONFIG.cacheNamewhenever the worker changes what it stores or how it keys it. Activation deletes the old cache, and visitors refill the new one as they browse. - Changing the strategy changes
sw.js, so it reaches visitors like any other worker update. The stored files stay valid under both strategies, socacheNamekeeps its version. - Kill switch: set
NEXT_PUBLIC_SERVICE_WORKER_ENABLED=falsein the app's.env.production, then build and deploy (public variables are inlined at build time). On each visitor's next page load, the page unregisters the worker and deletes its caches. Pages are never stored, so the new page code always arrives. - A broken worker is replaced by a fixed one: deploy the fix, and the next update check installs it.
- Never delete or rename
/sw.js. Browsers check that URL for updates, and without a valid script there, no new worker can replace the installed one. To retire the worker, turn it off and keep/sw.js. - Keep it off in development (
.env.development): a dev chunk can keep its name while its code changes, and the worker would serve the old code at least once. Test the worker in a production build (next buildandnext start) onlocalhost, which browsers treat as secure.
Serving the worker
- Each app's
next.config.tscallswriteServiceWorkerand addsSERVICE_WORKER_HEADERSfor/sw.jstoheaders()(code in Usage):Cache-Control: no-cache: browsers and the CDN revalidate it on every update check, so a new worker reaches visitors at their next navigation. Never give it the immutable header that fonts and the sprite get, and make the CDN honorno-cachefor it.Content-Security-Policy: default-src 'self'; script-src 'self': the worker can't load or fetch anything from another origin.
proxy.ts's matcher leaves out/sw.jsand/manifest.webmanifest. Browsers refuse a worker script behind a redirect, and a locale or auth redirect would break registration.- Each app has its own origin and is served from the origin's root, as the root paths of its fonts and sprite already require. Two apps on one origin would share one worker scope and one cache.
Measuring
- Every web-vitals report says whether a service worker controlled the page:
navigator.serviceWorker?.controller ? 'controlled' : 'none', sent by the analytics integration with eachuseReportWebVitalsmetric. - Compare the p75 of LCP, FCP, TTFB, and INP for controlled and uncontrolled page loads in every release review. When controlled loads are slower, turn the worker off and fix it.
Web app manifest
- Each app has
app/manifest.ts. Next.js serves it at/manifest.webmanifestand adds the<link rel="manifest">. It exportsdynamic = 'force-dynamic', like every metadata route (b2c-b2b.md). - Its fixed fields live in
configs/pwa.ts:id: '/', which keeps the installed app's identity ifstart_urlchanges;start_url: '/';scope: '/';display: 'standalone';background_color;theme_color; and the icons. name,short_name, anddescriptioncome from i18next. Browsers fetch the manifest without cookies, so it can't follow the visitor's locale cookie: use the app's default locale, and setlanganddirfrom it.background_colorandtheme_colorare the light theme's hex values for the page surface and the brand color in islandtheme.css. The manifest can't read CSS variables, so change both files together. The root layout'sgenerateViewportsetsthemeColorfor the theme the server chose.- Icons are PNG files in the app's
public/pwa/: 192×192, 512×512, and a 512×512maskableicon whose logo sits in the center 80%.app/apple-icon.png(180×180) covers iOS. The worker doesn't store them, because they're images.
Not in this lib
| Not here | Why |
|---|---|
| Pages, RSC payloads, and an offline page | Every page renders fresh per request, and auth-dependent UI renders in the browser. A stored page would be stale, or another visitor's |
| API data | The TanStack Query cache holds server state, and the HTTP lib owns retries |
| Images, media, and other SVGs | They're many, large, and different per page; the HTTP cache and the CDN keep them. Only the sprite serves every page |
| Cross-origin files and third-party scripts | Opaque responses can't be checked, and they count heavily against the storage quota |
| Push, background sync, and a custom install prompt | Product features: each needs product design, its own worker code, and a recorded decision |
Implementation
constants.ts
import type { ServiceWorkerConfig } from './types';
export const SERVICE_WORKER_URL = '/sw.js';
export const SERVICE_WORKER_SCOPE = '/';
export const CACHE_NAME_PREFIX = 'pwa-';
export const SERVICE_WORKER_CONFIG: ServiceWorkerConfig = {
strategy: 'stale-while-revalidate', // the default; only the developer switches an app to 'cache-first'
cacheName: `${CACHE_NAME_PREFIX}assets-v1`, // raise v1 when the worker changes what it stores or how
cachePrefix: CACHE_NAME_PREFIX,
maxEntries: 200,
cacheLoadedMessage: 'pwa.cache-loaded',
paths: { static: '/_next/static/', fonts: '/fonts/', sprite: '/icons/symbol-defs.svg' },
};
export const SERVICE_WORKER_HEADERS: Readonly<Record<string, string>> = {
'Cache-Control': 'no-cache',
'Content-Security-Policy': "default-src 'self'; script-src 'self'",
};
pwa.ts
import { CACHE_NAME_PREFIX, SERVICE_WORKER_CONFIG, SERVICE_WORKER_SCOPE, SERVICE_WORKER_URL } from './constants';
import type { CacheLoadedMessage, ServiceWorkerOptions } from './types';
let options: ServiceWorkerOptions = { enabled: false };
export function configureServiceWorker(next: ServiceWorkerOptions): void {
options = next;
}
export function registerServiceWorker(): void {
if (typeof window === 'undefined') {
throw new Error('registerServiceWorker is browser-only; call it in an effect');
}
if (!('serviceWorker' in navigator)) return;
// Best effort: the site works the same without the worker.
void (options.enabled ? register() : unregister()).catch(() => undefined);
}
async function register(): Promise<void> {
const wasControlled = navigator.serviceWorker.controller !== null;
await loaded();
await navigator.serviceWorker.register(SERVICE_WORKER_URL, { scope: SERVICE_WORKER_SCOPE, updateViaCache: 'none' });
if (wasControlled) return;
// The page loaded before the worker controlled it, so the worker stores what the page already has.
const { active } = await navigator.serviceWorker.ready;
const message: CacheLoadedMessage = {
type: SERVICE_WORKER_CONFIG.cacheLoadedMessage,
urls: performance.getEntriesByType('resource').map((entry) => entry.name),
};
active?.postMessage(message);
}
async function unregister(): Promise<void> {
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(registrations.map((registration) => registration.unregister()));
const names = await caches.keys();
await Promise.all(names.filter((name) => name.startsWith(CACHE_NAME_PREFIX)).map((name) => caches.delete(name)));
}
function loaded(): Promise<void> {
if (document.readyState === 'complete') return Promise.resolve();
return new Promise((resolve) => window.addEventListener('load', () => resolve(), { once: true }));
}
service-worker.ts
// A classic script: no import or export, so writeServiceWorker can emit it as one file.
// writeServiceWorker writes SERVICE_WORKER_CONFIG above it.
declare const SERVICE_WORKER_CONFIG: import('./types').ServiceWorkerConfig;
type InstallEventWithRoutes = ExtendableEvent & {
addRoutes?: (rules: { condition: { requestMode: RequestMode }; source: 'network' }[]) => Promise<void>;
};
const worker = self as unknown as ServiceWorkerGlobalScope;
const { strategy, cacheName, cachePrefix, maxEntries, cacheLoadedMessage, paths } = SERVICE_WORKER_CONFIG;
function isStoredKind(url: URL): boolean {
if (url.origin !== worker.location.origin) return false;
const { pathname } = url;
if (pathname.startsWith(paths.static)) return pathname.endsWith('.js') || pathname.endsWith('.css');
if (pathname.startsWith(paths.fonts)) return pathname.endsWith('.woff2');
return pathname === paths.sprite;
}
function isStorable(response: Response): boolean {
return response.status === 200 && response.type === 'basic' && !response.redirected;
}
async function store(request: Request, response: Response): Promise<void> {
try {
const cache = await caches.open(cacheName);
if (new URL(request.url).pathname === paths.sprite) {
const versions = await cache.keys(request, { ignoreSearch: true });
await Promise.all(versions.map((version) => cache.delete(version)));
}
await cache.put(request, response);
const keys = await cache.keys();
await Promise.all(keys.slice(0, Math.max(0, keys.length - maxEntries)).map((key) => cache.delete(key)));
} catch {
// A full or blocked cache costs one network request next time, nothing more.
}
}
// Matching validators mean the same file. A response without one counts as changed.
function isSameFile(stored: Response, fresh: Response): boolean {
const validator = (response: Response) => response.headers.get('etag') ?? response.headers.get('last-modified');
const freshValidator = validator(fresh);
return freshValidator !== null && freshValidator === validator(stored);
}
async function fromNetwork(event: FetchEvent, stored?: Response): Promise<Response> {
const response = await fetch(event.request);
if (isStorable(response) && !(stored && isSameFile(stored, response))) {
event.waitUntil(store(event.request, response.clone()));
}
return response;
}
async function staleWhileRevalidate(event: FetchEvent): Promise<Response> {
const stored = await caches.match(event.request, { cacheName, ignoreVary: true });
const fresh = fromNetwork(event, stored);
if (!stored) return fresh;
// The check finishes after the response; when it fails, the stored copy stays.
event.waitUntil(fresh.then(() => undefined, () => undefined));
return stored;
}
async function cacheFirst(event: FetchEvent): Promise<Response> {
const stored = await caches.match(event.request, { cacheName, ignoreVary: true });
return stored ?? fromNetwork(event);
}
const respond = strategy === 'cache-first' ? cacheFirst : staleWhileRevalidate;
function toStoredKindUrl(value: unknown): URL | null {
if (typeof value !== 'string') return null;
try {
const url = new URL(value);
return isStoredKind(url) ? url : null;
} catch {
return null;
}
}
async function storeLoaded(urls: unknown[]): Promise<void> {
const wanted = urls.map(toStoredKindUrl).filter((url): url is URL => url !== null);
await Promise.all(
wanted.slice(0, maxEntries).map(async (url) => {
if (await caches.match(url.href, { cacheName, ignoreVary: true })) return;
// The page loaded it a moment ago, so the HTTP cache answers.
const response = await fetch(url.href).catch(() => null);
if (response && isStorable(response)) await store(new Request(url.href), response);
}),
);
}
worker.addEventListener('install', (event) => {
void worker.skipWaiting();
// Chromium sends navigations straight to the network, so the worker never starts only to let a page through.
// Other browsers use navigation preload (activate).
const routable = event as InstallEventWithRoutes;
if (!routable.addRoutes) return;
event.waitUntil(
routable.addRoutes([{ condition: { requestMode: 'navigate' }, source: 'network' }]).catch(() => undefined),
);
});
worker.addEventListener('activate', (event) => {
event.waitUntil(
(async () => {
await worker.registration.navigationPreload?.enable().catch(() => undefined);
const names = await caches.keys();
await Promise.all(
names.filter((name) => name.startsWith(cachePrefix) && name !== cacheName).map((name) => caches.delete(name)),
);
await worker.clients.claim();
})(),
);
});
worker.addEventListener('fetch', (event) => {
const { request } = event;
if (request.method !== 'GET') return;
if (request.mode === 'navigate') {
// Passed through, never stored.
event.respondWith(Promise.resolve(event.preloadResponse).then((preloaded?: Response) => preloaded ?? fetch(request)));
return;
}
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') return;
if (isStoredKind(new URL(request.url))) event.respondWith(respond(event));
});
worker.addEventListener('message', (event) => {
const message = event.data as Partial<import('./types').CacheLoadedMessage> | null;
if (message?.type === cacheLoadedMessage && Array.isArray(message.urls)) event.waitUntil(storeLoaded(message.urls));
});
event.waitUntilinsidefromNetworkruns after anawait. The spec allows it while the event has a pending promise: therespondWithpromise, or the background check thatstaleWhileRevalidatepasses towaitUntilfirst.cache.keys()lists entries in the order they were stored, so the slice deletes the oldest. The worker writes an entry again only when its file changed, so the order stays first in, first out.
service-worker-plugin.ts. It runs from source when next.config.ts loads, so __dirname is the lib's folder.
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import ts from 'typescript';
import { SERVICE_WORKER_CONFIG, SERVICE_WORKER_URL } from './constants';
import type { ServiceWorkerPluginOptions } from './types';
export function writeServiceWorker({ publicDir, strategy }: ServiceWorkerPluginOptions): void {
const source = readFileSync(path.join(__dirname, 'service-worker.ts'), 'utf8');
const { outputText } = ts.transpileModule(source, {
compilerOptions: { target: ts.ScriptTarget.ES2022, removeComments: true },
});
const config = { ...SERVICE_WORKER_CONFIG, strategy: strategy ?? SERVICE_WORKER_CONFIG.strategy };
const script = `const SERVICE_WORKER_CONFIG = ${JSON.stringify(config)};\n${outputText}`;
const file = path.join(publicDir, SERVICE_WORKER_URL);
// The same bytes again would restart the dev server's file watchers for nothing.
if (existsSync(file) && readFileSync(file, 'utf8') === script) return;
writeFileSync(file, script);
}
Usage
apps/<app>/src/env/env.client.ts declares the flag. Like every env value, it's required and has no default (lib-env.md).
// in schema
NEXT_PUBLIC_SERVICE_WORKER_ENABLED: v.pipe(v.picklist(['true', 'false']), v.transform((value) => value === 'true')),
// in runtimeEnv
NEXT_PUBLIC_SERVICE_WORKER_ENABLED: process.env.NEXT_PUBLIC_SERVICE_WORKER_ENABLED,
.env.production sets NEXT_PUBLIC_SERVICE_WORKER_ENABLED=true, and .env.development sets it to false.
bootstrap.client.ts
configureServiceWorker({ enabled: clientEnv.NEXT_PUBLIC_SERVICE_WORKER_ENABLED });
platforms/<platform>/src/app/app-shell/AppShell.tsx, beside its other startup effects:
useEffect(() => {
registerServiceWorker();
}, []);
apps/<app>/next.config.ts. Load the plugin the way the island plugins are loaded: through jiti when the config can't resolve workspace TypeScript. The call passes no strategy, so the worker uses stale-while-revalidate; only a developer who explicitly chose cache first adds strategy: 'cache-first'.
import path from 'node:path';
import { SERVICE_WORKER_HEADERS, SERVICE_WORKER_URL, writeServiceWorker } from '@project/libs/pwa/plugin';
writeServiceWorker({ publicDir: path.join(__dirname, 'public') });
// inside headers()
{
source: SERVICE_WORKER_URL,
headers: Object.entries(SERVICE_WORKER_HEADERS).map(([key, value]) => ({ key, value })),
},
apps/<app>/src/configs/pwa.ts. The colors are the light theme's --surface-page and --action-primary values from island theme.css.
import type { MetadataRoute } from 'next';
export const PWA_MANIFEST = {
id: '/',
start_url: '/',
scope: '/',
display: 'standalone',
background_color: '#f4f6fa',
theme_color: '#2563eb',
icons: [
{ src: '/pwa/icon-192.png', sizes: '192x192', type: 'image/png' },
{ src: '/pwa/icon-512.png', sizes: '512x512', type: 'image/png' },
{ src: '/pwa/icon-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
],
} satisfies MetadataRoute.Manifest;
apps/<app>/src/app/manifest.ts. getServerI18n and DEFAULT_LOCALE stand for the app's per-request i18next setup in src/i18n/; match their real names.
import type { MetadataRoute } from 'next';
import { PWA_MANIFEST } from '../configs';
import { DEFAULT_LOCALE, getServerI18n } from '../i18n';
export const dynamic = 'force-dynamic';
export default async function manifest(): Promise<MetadataRoute.Manifest> {
// Browsers fetch the manifest without cookies, so it uses the default locale.
const i18n = await getServerI18n(DEFAULT_LOCALE);
return {
...PWA_MANIFEST,
name: i18n.t('app:pwa.name'),
short_name: i18n.t('app:pwa.short-name'),
description: i18n.t('app:pwa.description'),
lang: DEFAULT_LOCALE,
dir: i18n.dir(DEFAULT_LOCALE),
};
}
Acceptance checklist
For building or changing the lib:
[ ] Once the worker is active, every /_next/static/ JS and CSS file, /fonts/*.woff2 file, and /icons/symbol-defs.svg?v=<N> the page requests is served from the cache without waiting for the network
[ ] By default (no strategy passed), each served copy starts one background check; a response with the same ETag or Last-Modified isn't written, a changed one replaces the copy, and a failed check keeps it
[ ] With strategy 'cache-first', a stored file is served with no network request at all
[ ] Nothing else is stored: pages, RSC payloads, API responses, images, /_next/static/media/*, other SVGs, cross-origin files, non-GET requests, and partial, redirected, or error responses
[ ] Storing symbol-defs.svg?v=2 deletes symbol-defs.svg?v=1
[ ] The cache never keeps more than maxEntries entries, and the oldest go first
[ ] Navigations always reach the network: Chromium sends them past the worker, other browsers get the navigation preload response, and none is stored
[ ] After the first registration, the matching files the page already loaded are stored from the HTTP cache, with no new network requests
[ ] A changed sw.js activates at once, deletes every pwa- cache except the current one, and controls the open pages
[ ] With enabled: false, the next page load unregisters the worker and deletes every pwa- cache
[ ] registerServiceWorker throws the browser-only error on the server; configureServiceWorker doesn't
[ ] Without service worker support, or when registration fails, the site works and shows no error
[ ] /sw.js is served with SERVICE_WORKER_HEADERS and isn't redirected by proxy.ts; writeServiceWorker rewrites it only when its content changes
[ ] An Nx cache hit on the app's build restores public/sw.js
[ ] service-worker.ts type-checks with the WebWorker lib and has no import, export, or importScripts