feat: update skill
This commit is contained in:
parent
495f800f1f
commit
b85b05861f
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
name: front-end-architect
|
||||
description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites (Next.js App Router, server rendering, web vitals, bundle and hydration budgets for millions of daily visitors). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and token refresh; error handler; env; cookie; local storage), integrations, and tools, with kebab-case naming, tree-shakeable exports with server and client entries, and DDD features (entities, repositories, caches, actions, models), on Tailwind v4 with cva, valibot, react-hook-form, zustand, i18next, and sonner, and keeps each project's architecture and design decision records (ADR, DDR). Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects in these monorepos, when planning a feature, when the user states a lasting project rule or asks to record or change a decision, or when another skill such as a product designer or architect needs front-end input.
|
||||
description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites (Next.js App Router, server rendering, web vitals, bundle and hydration budgets for millions of visitors). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and refresh; error handler; env; cookie; local storage; PWA service worker; JSON-LD structured data), integrations, and tools, with kebab-case naming, tree-shakeable exports with server and client entries, and DDD features (entities, repositories, caches, actions, models), on Tailwind v4 with cva, valibot, react-hook-form, zustand, i18next, and sonner, and keeps each project's decision records (ADR, DDR). Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects, when planning a feature, when the user states a lasting rule or asks to record or change a decision, or when another skill (product designer, architect) needs front-end input.
|
||||
---
|
||||
|
||||
# Front-end Architect
|
||||
|
|
@ -23,7 +23,7 @@ How you work:
|
|||
- Server entry: every project except apps has `src/server.ts`.
|
||||
- Critical: a fresh server render per request with no server cache, web vitals, bundle and chunk size, and hydration and navigation speed.
|
||||
|
||||
Read the playbook before designing or writing code: [references/b2c-b2b.md](references/b2c-b2b.md). When the work changes what the user sees or what search engines read (a page, template, organism, form, copy, upload, image, font, icon, or metadata), also read [references/ui-rules.md](references/ui-rules.md): UX, SEO, images, fonts, and the icon sprite.
|
||||
Read the playbook before designing or writing code: [references/b2c-b2b.md](references/b2c-b2b.md). When the work changes what the user sees or what search engines read (a page, template, organism, form, copy, upload, image, font, icon, metadata, or structured data), also read [references/ui-rules.md](references/ui-rules.md): UX, SEO, images, fonts, and the icon sprite.
|
||||
|
||||
## 2. Stack
|
||||
|
||||
|
|
@ -43,6 +43,8 @@ Read the playbook before designing or writing code: [references/b2c-b2b.md](refe
|
|||
| Lint and format | oxlint, prettier | ESLint runs module-boundary rules only |
|
||||
| TS scripts and configs | jiti | Runs `tools/` scripts and TypeScript config files without a build step |
|
||||
| Icons | svgo | Through island's `icon-sprite-plugin`, into `symbol-defs.svg`, which no step hashes; linked with `?v=<N>` |
|
||||
| Service worker | Native Service Worker and Cache APIs | Only through the pwa lib: one worker per app that stores JS, CSS, fonts, and `symbol-defs.svg`, nothing else. No Workbox or Serwist |
|
||||
| Structured data | schema.org JSON-LD | Only through the json-ld lib's builders, rendered on the server by island's `JsonLd` primitive. No schema-dts or next-seo |
|
||||
|
||||
TanStack Query is implied by `configs/react-query.ts`; confirm the repo uses it before adding it. Don't add any dependency outside this stack without stating why and getting approval.
|
||||
|
||||
|
|
@ -54,13 +56,15 @@ The rules below are enough for work inside existing projects and features. Read
|
|||
- Component placement (its atomic level and the project and folder it belongs in), before you add or move a component: only the "Choosing where a component goes" section of [references/project-structure.md](references/project-structure.md#choosing-where-a-component-goes)
|
||||
- Code patterns, one section at a time: read only the section for the layer you write (island component, tokens, repository, action, form and model, mutation, store, persisted store, env), as its Contents line lists. Copy an existing file of the same kind when the repo has one: [references/code-patterns.md](references/code-patterns.md)
|
||||
|
||||
Shared libs have full specs. Read the matching one only when you build or change the lib itself, or when a feature needs lib behavior that "Env, HTTP, cookies, and storage" below doesn't describe. To use a lib from a feature, that section and code-patterns.md are enough:
|
||||
Shared libs have full specs. Read the matching one only when you build or change the lib itself, or when a feature needs lib behavior that "Env, HTTP, cookies, storage, the service worker, and structured data" below doesn't describe. To use a lib from a feature, that section and code-patterns.md are enough:
|
||||
|
||||
- HTTP client: [references/lib-http.md](references/lib-http.md)
|
||||
- Error handler: [references/lib-error-handler.md](references/lib-error-handler.md)
|
||||
- Env: [references/lib-env.md](references/lib-env.md)
|
||||
- Cookies: [references/lib-cookie.md](references/lib-cookie.md)
|
||||
- Local storage: [references/lib-local-storage.md](references/lib-local-storage.md)
|
||||
- PWA and the service worker, also whenever work touches `/sw.js`, the web app manifest, or what the browser keeps between visits: [references/lib-pwa.md](references/lib-pwa.md)
|
||||
- JSON-LD structured data, also whenever work adds an indexable page type or changes what a page tells search engines about the business, a product, its price, or its policies: [references/lib-json-ld.md](references/lib-json-ld.md)
|
||||
|
||||
Error handling, patterns, and refactoring have their own references. Read each one only when its trigger applies:
|
||||
|
||||
|
|
@ -110,7 +114,7 @@ Error handling, patterns, and refactoring have their own references. Read each o
|
|||
- Client side (the parts of a page that load in the browser): repository → model → UI. Every page has a skeleton (`loading.tsx`). Every part that loads on its own has its own `<Suspense>` with a same-size skeleton and its own part boundary (EB-S), so one slow or failing part never blocks the others.
|
||||
- Server side: repository → cache → server components. Pages, `generateMetadata`, and server components read data only through caches. A client component gets server data as props, or through React Query hydration when it must stay live. Details: [references/b2c-b2b.md](references/b2c-b2b.md#data-flow).
|
||||
|
||||
**Env, HTTP, cookies, and storage**
|
||||
**Env, HTTP, cookies, storage, the service worker, and structured data**
|
||||
|
||||
- Env (`packages/libs/src/env`): only the app's `env/` files read `process.env`, through `createClientEnv` (public) and `createServerEnv` (server only). Other projects read their own values with `getEnv`, filled by the app's bootstrap. Libs never read env; the bootstrap passes their settings through `configure`.
|
||||
- No project hard-codes an env value: a value that changes between environments, such as a service or CDN address, a key, a third-party ID, or a feature flag. Not as a literal, a fallback (`?? 'http://localhost:3000'`), or a schema default. Every env value comes from the `.env` of the app that serves it, and only apps have `.env` files. Values that are the same in every environment stay in `constants/`.
|
||||
|
|
@ -121,6 +125,10 @@ Error handling, patterns, and refactoring have their own references. Read each o
|
|||
- Cookies (`packages/libs/cookie`, the `cookie` instance): only small values the server needs on the request, such as locale and theme. Never tokens: auth cookies are HttpOnly and belong to the server. Browser only; server code reads cookies with `next/headers`.
|
||||
- Local storage (`packages/libs/local-storage`, the `storage` instance): client-only, non-critical data under the app's key prefix, and the storage behind persisted zustand stores. Never tokens or personal data.
|
||||
- `cookie` and `storage` are never read during render, at module top level, or in repositories.
|
||||
- Service worker (`packages/libs/pwa`): each app serves one worker at `/sw.js`, written by the lib's `writeServiceWorker` and registered from the `AppShell` when the app's env turns it on. It stores only JS and CSS from `/_next/static/`, fonts from `/fonts/`, and `/icons/symbol-defs.svg`, by exact URL, stale-while-revalidate unless the developer explicitly chooses cache first. Pages, RSC payloads, API data, images, and every other SVG reach the network untouched.
|
||||
- Storing any other kind of URL needs a recorded decision. `/sw.js` is never renamed or removed; turning the env flag off unregisters the worker for every visitor.
|
||||
- Structured data (`packages/libs/json-ld`, server only): every indexable page renders one schema.org JSON-LD graph with island's `JsonLd`, in its page entry, from the data its first paint already awaits. The home page describes the business (`OnlineStore`) and the website from the app's `configs/seo.ts`; other page types get theirs from a builder in the platform's `app/json-ld/`, such as the product with its offer, rating, and breadcrumb.
|
||||
- The graph says only what the page shows, the same for every visitor: never a member or personal price, and no rating on the business itself. `noindex` pages and not-found, no-access, and error states render none.
|
||||
|
||||
**Design system (island)**
|
||||
|
||||
|
|
@ -135,9 +143,10 @@ Error handling, patterns, and refactoring have their own references. Read each o
|
|||
|
||||
- Separate concerns: components render, models orchestrate, actions run operations, repositories talk to the network through their feature's HTTP client, and caches share server reads within a request. No `fetch` outside the HTTP lib.
|
||||
- Keep one source of truth per kind of state: server state in the query cache, URL state in the URL, form state in react-hook-form, shared client state in zustand, and ephemeral UI state in the component. Never copy one into another.
|
||||
- Deploys never break open tabs: build once per release, mark it with `NEXT_DEPLOYMENT_ID` from CI, and keep old releases' `/_next/static/` files for 30 days ([references/b2c-b2b.md](references/b2c-b2b.md#deploys-and-version-skew)).
|
||||
- Keep the UI stable: colocate state, split large contexts, never let an update unmount and remount a visible subtree, and never use random values or array indexes as keys for dynamic lists.
|
||||
- Model multi-step flows (wizards, imports, bulk actions) as explicit states, such as `idle → validating → uploading → processing → done | failed`, never as a set of booleans.
|
||||
- Handle errors with one model ([references/error-handling.md](references/error-handling.md)): EB-W at the app root only, a page-size EB-S inside the shell for every page, and a part-size EB-S around every part that loads on its own, so one broken part never takes down the page. A failed read shows in its boundary or as an empty state (404 and 403) and never toasts. A failed action shows an error toast with its hint or a reference ID and the retry its cause allows. `ABORTED` and 401 stay silent.
|
||||
- Handle errors with one model ([references/error-handling.md](references/error-handling.md)): EB-W at the app root only, a page-size EB-S inside the shell for every page, and a part-size EB-S around every part that loads on its own, so one broken part never takes down the page. A failed read shows in its boundary or as an empty state (404 and 403) and never toasts. A failed action shows an error toast with its hint or a reference ID and the retry its cause allows. `ABORTED` and 401 stay silent. A chunk that fails to load after a deploy is outdated: a page reloads once, a part or toast offers Reload page, and nothing is reported.
|
||||
- Every text comes from i18next and is a simple, complete description of its purpose ("Save changes to this category", not "Save"). Support RTL and LTR: set `lang` and `dir` from the locale, and use logical utilities (`ms-*`, `pe-*`, `start-*`) instead of left and right.
|
||||
- Meet WCAG 2.1 AA: 4.5:1 text contrast, visible focus rings, full keyboard operation, and an `aria-label` on every icon-only button.
|
||||
|
||||
|
|
@ -196,6 +205,8 @@ Structure
|
|||
[ ] Each new or moved part went through rendering-patterns.md's "Choosing where a part loads"; every deferred part and its trigger is written in the PR
|
||||
[ ] The server render is the same for every visitor; every auth-dependent page or part renders in the browser behind a same-size skeleton, unless the developer asked otherwise and the PR says so
|
||||
[ ] Fonts and the icon sprite keep fixed names that no step hashes; every sprite change raised ICON_SPRITE_VERSION in the same commit
|
||||
[ ] The service worker stores only JS, CSS, fonts, and symbol-defs.svg, stale-while-revalidate unless the developer explicitly chose cache first; /sw.js keeps its name and its no-cache header
|
||||
[ ] Every indexable page renders one JSON-LD graph through the json-ld lib and island's JsonLd, from its first-paint data; it says only what the page shows, the same for every visitor; noindex pages and error states have none
|
||||
[ ] Refactors are in their own commits, and the PR states how unchanged behavior was checked; smells noticed but not fixed are listed as debt
|
||||
[ ] Code follows every accepted decision in docs/decisions; lasting decisions made in this work are recorded
|
||||
|
||||
|
|
@ -221,4 +232,4 @@ Every review comment names the rule, shows the problem, and proposes the fix. Fo
|
|||
|
||||
Name a code smell and its technique, with the target layer or file, as [references/refactoring.md](references/refactoring.md#review-comments) does. A smell is a suggestion; when it also breaks a rule on the list below, lead with that rule, mark it blocking, and name the smell in the body. In a feature PR, raise smells only in the code the PR touches. Flag a pattern from the "Not used here" list in [references/design-patterns.md](references/design-patterns.md#not-used-here) with its alternative. Never flag the smells that refactoring.md marks as intended.
|
||||
|
||||
Block a merge only for: code that breaks an accepted project decision; a boundary or layer violation; a client-side dependency in a repository; server-only code reachable from a client bundle; tokens or personal data readable by JavaScript (a non-HttpOnly cookie or local storage); stale cache after a mutation; a sprite change without a version bump, a font changed under its old name, or a font or sprite name that a build step hashes; missing error handling; missing loading or empty states; inaccessible contrast; UI that flickers on update; a server-side cache; a server render that depends on auth without the developer's explicit request; a page not rendered per request, or a web-vitals or bundle-budget regression. Everything else is a suggestion with a rationale.
|
||||
Block a merge only for: code that breaks an accepted project decision; a boundary or layer violation; a client-side dependency in a repository; server-only code reachable from a client bundle; tokens or personal data readable by JavaScript (a non-HttpOnly cookie or local storage); stale cache after a mutation; a sprite change without a version bump, a font changed under its old name, or a font or sprite name that a build step hashes; a service worker that stores anything beyond JS, CSS, fonts, and the icon sprite, or a renamed or removed `/sw.js`; structured data that says what the page doesn't show or depends on the viewer, or an `application/ld+json` script written outside island's `JsonLd`; missing error handling; missing loading or empty states; inaccessible contrast; UI that flickers on update; a server-side cache; a server render that depends on auth without the developer's explicit request; a page not rendered per request, or a web-vitals or bundle-budget regression. Everything else is a suggestion with a rationale.
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
Public websites with 1–20 million visitors a day, like Amazon, eBay, and Digikala. Every kilobyte and millisecond is multiplied by millions of sessions. Most visitors arrive from search on mid-range phones, and many are logged out. Performance and SEO decide the architecture, the server renders every page fresh and caches nothing, and the codebase must stay maintainable as teams and features grow.
|
||||
|
||||
Contents: Targets · No server cache · Rendering · Server and client entries · Data flow · Errors · State and auth · Bundle and code splitting · Hydration and navigation · Responsiveness and monitoring · Example: caches, page, and parts · Definition of Done
|
||||
Contents: Targets · No server cache · Rendering · Server and client entries · Data flow · Errors · State and auth · Bundle and code splitting · Hydration and navigation · Deploys and version skew · Responsiveness and monitoring · Example: caches, page, and parts · Definition of Done
|
||||
|
||||
## Targets
|
||||
|
||||
|
|
@ -26,8 +26,16 @@ The Next.js server renders a fresh page for every request and keeps nothing betw
|
|||
- Keep Cache Components (`cacheComponents` in `next.config.ts`) off, because it prerenders a static shell at build time. Every root layout declares `export const dynamic = 'force-dynamic'`, which renders each route at request time and sends every `fetch` with `no-store`. Metadata routes (`sitemap.ts`, `robots.ts`, generated icons and Open Graph images) are cached by default and no layout covers them, so each one declares it too.
|
||||
- Never use `'use cache'`, `unstable_cache`, `fetch` caching (`cache: 'force-cache'`, `next: { revalidate, tags }`), the `revalidate` segment config, `dynamic = 'force-static'` or `'error'`, or `generateStaticParams`. The HTTP lib sends every server request with `cache: 'no-store'` (see [lib-http.md](lib-http.md#server-side)).
|
||||
- Never keep back-end data or rendered output in module scope, such as a `Map`, an LRU, or a memoized promise. Settings made once at startup, like env and the root `http` client, are fine.
|
||||
- Caches that end with the request are fine: React `cache()` (the features' `caches/`) and the per-request `QueryClient`. So are caches in the browser, like the TanStack Query cache and the router cache.
|
||||
- Caches that end with the request are fine: React `cache()` (the features' `caches/`) and the per-request `QueryClient`. So are caches in the browser: the TanStack Query cache, the router cache, and the service worker's cache, which holds only JS, CSS, fonts, and the icon sprite, never pages or data ([lib-pwa.md](lib-pwa.md)).
|
||||
- Nothing needs revalidating. After a mutation that changes server-rendered content, call `router.refresh()` and the server renders the page again.
|
||||
- Every app's `next.config.ts` turns on fetch logging with full URLs, so the dev server prints each server `fetch` with its whole URL, status, time, and cache result. That shows which back-end calls a page makes and proves each one skips the cache:
|
||||
|
||||
```ts
|
||||
logging: {
|
||||
fetches: { fullUrl: true },
|
||||
},
|
||||
```
|
||||
|
||||
- Every request pays for a full render, so keep it cheap: stream slow parts, fetch in parallel, and when a back-end call is slow, fix or cache it in the back end, never in Next.js.
|
||||
|
||||
## Rendering
|
||||
|
|
@ -39,11 +47,12 @@ The Next.js server renders a fresh page for every request and keeps nothing betw
|
|||
- Pages are thin entrypoints. The page resolves the device on the server and renders the mobile or the desktop template. Only that view's client code ships, the markup matches on hydration, and nothing shifts. Never choose between layouts with viewport checks in components.
|
||||
- Stream: add `loading.tsx` per route group and `<Suspense>` with same-size skeletons around slow parts, each inside its own `PartBoundary`. One slow or failing backend call must never block the whole page. Record each route's streamed and auth-dependent parts in the plan.
|
||||
- Server code reads data through the features' caches, so `generateMetadata`, the page, and every server component share one request per distinct call (see Data flow).
|
||||
- Every indexable page renders its JSON-LD in the page entry, outside every `<Suspense>`, from the data its first paint already awaits, so structured data is in the initial HTML and costs no extra request ([lib-json-ld.md](lib-json-ld.md#rendering)).
|
||||
|
||||
## Server and client entries
|
||||
|
||||
- Each project except apps exposes `src/index.ts`, safe to import anywhere, and `src/server.ts`, server only. `server.ts` starts with `import 'server-only';` and is exported as `@project/<name>/server`. Client code imports only `index.ts` entries, and `index.ts` never re-exports from `server.ts`.
|
||||
- `server.ts` holds server-only capabilities: caches, page data loaders, SEO builders, device detection, the server HTTP configuration, and server-side integrations. Server-only files are exported only from `server.ts`, never from a module's `index.ts`.
|
||||
- `server.ts` holds server-only capabilities: caches, page data loaders, SEO builders (the platform's `app/json-ld/`), device detection, the server HTTP configuration, and server-side integrations. Server-only files are exported only from `server.ts`, never from a module's `index.ts`.
|
||||
- Repositories have no client-side dependencies, so they are exported from `index.ts` and run on both sides.
|
||||
- A server page loader that combines several caches for one page's first paint sits in that page's `models/<page>/` folder (`load-<page>-page.ts`) and is exported only through `server.ts`.
|
||||
- `bootstrap.server.ts` must run before server rendering: import it at the top of every root layout. `bootstrap.client.ts` must run before client components render, both during SSR and in the browser: import it first in the app's root client component, the one that renders the platform's `AppShell`. Client components render in a separate module graph, so values set by server-only code are invisible to them. Make both bootstraps idempotent.
|
||||
|
|
@ -115,10 +124,23 @@ The model, the boundaries, and their code are in [error-handling.md](error-handl
|
|||
- Navigate with `next/link` so routes prefetch. Keep the header and footer in layouts, so navigation re-renders only the page segment.
|
||||
- Protect INP: keep event handlers light, wrap non-urgent updates in `startTransition`, debounce search input by 250–400 ms, and for long interactive lists try `content-visibility` first; a virtualization library needs approval ([rendering-patterns.md](rendering-patterns.md)).
|
||||
|
||||
## Deploys and version skew
|
||||
|
||||
A deploy doesn't end the sessions already open. A tab keeps running the old release's JavaScript until it reloads, while the servers already run the new release. These rules keep that tab working, or move it to the new release with a normal page load instead of an error.
|
||||
|
||||
- Build once per release, and run that same output on every instance, so all of them share one build ID and one set of asset files. Never build on each server.
|
||||
- Mark every release with Next.js's deployment ID. CI sets `NEXT_DEPLOYMENT_ID` to the release's commit SHA when it runs `next build`; Next.js reads it itself. It adds `?dpl=<id>` to its asset URLs and sends the ID with every client-side navigation. When an old tab navigates and the IDs differ, Next.js does a full page load into the new release instead of a client-side navigation. The value changes on every release, so it comes from CI, never from `.env` or a literal `deploymentId` in `next.config.ts`; no app code reads it.
|
||||
- Keep old releases' static files. Serve `/_next/static/` on the app's own origin from storage that every release adds to: on deploy, copy the build's `.next/static/` into it without deleting what's there, and delete a release's files only 30 days after it stopped serving. An old tab that loads a lazy chunk (`next/dynamic`, `LoadOnVisible`, or a route it hasn't visited) then still finds it. Replacing `.next/` in place, as a plain `next start` deploy does, deletes the old chunks, and those loads fail with 404. Keep the same origin: the service worker stores only same-origin files ([lib-pwa.md](lib-pwa.md)).
|
||||
- During a rolling deploy, old and new instances serve side by side. Shared static storage lets every page find its chunks whichever instance rendered it, and a navigation that reaches the other release gets the deployment ID's full page load.
|
||||
- The back-end contract changes compatibly: each back-end release keeps serving the previous front-end release for as long as its tabs live (additive fields, old endpoints kept), and each front-end release works with the back end it may meet during a rolling deploy.
|
||||
- Feature actions run in the browser and Server Actions aren't used, so no action ID goes stale between releases.
|
||||
- The service worker keeps the chunks each visitor already loaded, so an old tab often gets them from the device, and it never caches pages, so a reload always lands on the current release ([lib-pwa.md](lib-pwa.md)).
|
||||
- What still fails, a chunk missing despite these rules, is classified as outdated by the error handler. A page or app boundary reloads the page once, a part boundary and an action's toast offer Reload page, and nothing is reported ([error-handling.md](error-handling.md#boundaries)). Watch 404s on `/_next/static/` in the CDN logs after each deploy instead: a rise means old files were deleted too early.
|
||||
|
||||
## Responsiveness and monitoring
|
||||
|
||||
- Each route has a mobile and a desktop template, and each template stays fluid across its device range. Touch targets are at least 44×44 px on mobile.
|
||||
- Report field web vitals per route (`useReportWebVitals` into the analytics integration), report errors through the error handler to the Sentry integration (`instrumentation.ts` on the server, `bootstrap.client.ts` in the browser), and review p75 per release.
|
||||
- Report field web vitals per route (`useReportWebVitals` into the analytics integration), each with whether the service worker controlled the page ([lib-pwa.md](lib-pwa.md#measuring)), report errors through the error handler to the Sentry integration (`instrumentation.ts` on the server, `bootstrap.client.ts` in the browser), and review p75 per release.
|
||||
|
||||
## Example: caches, page, and parts
|
||||
|
||||
|
|
@ -129,6 +151,7 @@ In [page-example.md](page-example.md). Read it when you add a new page, or a par
|
|||
|
||||
```
|
||||
[ ] Fresh page per request: Cache Components off; every root layout and metadata route exports dynamic = 'force-dynamic'
|
||||
[ ] next.config.ts sets logging: { fetches: { fullUrl: true } }
|
||||
[ ] No server cache: no 'use cache', unstable_cache, fetch caching, revalidate, or generateStaticParams; no back-end data kept in module scope
|
||||
[ ] Server code reads data only through caches with primitive arguments; no page, loader, or server component calls a repository directly
|
||||
[ ] Each client part gets server data as props or through query hydration; server prefetches call the cache
|
||||
|
|
@ -144,5 +167,7 @@ In [page-example.md](page-example.md). Read it when you add a new page, or a par
|
|||
[ ] No hydration warnings; LCP image not lazy; images, fonts, and banners cause no layout shift
|
||||
[ ] No store writes during server render; per-request QueryClient on the server
|
||||
[ ] No cookie or local-storage reads during render; persisted stores rehydrate after mount
|
||||
[ ] Metadata, canonical URL, hreflang, and structured data where relevant
|
||||
[ ] Metadata, canonical URL, and hreflang; every indexable page's JSON-LD follows lib-json-ld.md and passes the Rich Results Test
|
||||
[ ] Each release is built once, runs the same output on every instance, and is marked with NEXT_DEPLOYMENT_ID from CI
|
||||
[ ] /_next/static/ keeps every release's files until 30 days after that release stopped serving
|
||||
```
|
||||
|
|
|
|||
|
|
@ -155,6 +155,18 @@ This is an excerpt. The real file defines every semantic token the components us
|
|||
@import './fonts.css';
|
||||
@import './utilities.css';
|
||||
@source '../';
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* {
|
||||
scroll-behavior: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`styles/fonts.css`. Each `src` is a root path to the file in the app's `public/fonts/`, so no build step renames it ([ui-rules.md](ui-rules.md#fonts-and-the-icon-sprite)). The fallback face is a local font resized to the web font's metrics, so the swap doesn't shift layout. Measure the override values once for each face, and list the fallback after the web font in `--font-sans` in `theme.css`.
|
||||
|
|
@ -393,7 +405,9 @@ export function showActionError(error: unknown, { t, failedMessage, retry, reloa
|
|||
? { label: t('errors:action.try-again'), onClick: retry }
|
||||
: errorClass.retry === 'reload' && reload
|
||||
? { label: t('errors:action.reload'), onClick: reload }
|
||||
: undefined;
|
||||
: errorClass.retry === 'reload-page'
|
||||
? { label: t('errors:action.reload-page'), onClick: () => window.location.reload() }
|
||||
: undefined;
|
||||
|
||||
toast.error(failedMessage, {
|
||||
id: `action-error:${failedMessage}`,
|
||||
|
|
|
|||
|
|
@ -34,9 +34,9 @@ Reuse these before you add anything.
|
|||
| Module | Every module's `index.ts`; `server.ts` for server-only code | Every module. Re-export the public API by name and keep the rest private: never `export *`, never import another module's internal file, and never re-export `server.ts` from `index.ts` ([project-structure.md](project-structure.md#exports-and-tree-shaking)) |
|
||||
| Singleton | The root `http`, `cookie`, `storage`, `eventEmitter`, zustand stores, and the browser `QueryClient` from `getQueryClient()` | For a service the whole app shares: a module instance that the bootstrap configures (`export const cookie = new CookieAdapter()`), never a class with `getInstance`. On the server one instance serves every request, so per-request objects come from a function (a new `QueryClient` per `getQueryClient()` call, a per-request i18next instance), and nothing writes to a store during server render ([b2c-b2b.md](b2c-b2b.md#state-and-auth)) |
|
||||
| Factory functions | `createHttpClient`, `createClientEnv`, `createServerEnv`, `makeQueryClient`, and key factories such as `productKeys` | When several callers build the same kind of object from different inputs: a function that returns a new object or closure. Query keys always come from the repository's key factory ([code-patterns.md](code-patterns.md#repository)). Don't add a factory for an object built in one place |
|
||||
| Adapter | `CookieAdapter` over `document.cookie`; each repository's `mappers.ts`; each integration over its vendor API | At a boundary whose shape you don't own. Translate once, at the edge, so no `*Dto`, vendor type, or cookie string syntax crosses it. Don't adapt two of your own modules to each other; change one of them |
|
||||
| Adapter | `CookieAdapter` over `document.cookie`; each repository's `mappers.ts`; each integration over its vendor API; the json-ld lib over the schema.org vocabulary | At a boundary whose shape you don't own. Translate once, at the edge, so no `*Dto`, vendor type, cookie string syntax, or schema.org shape crosses it. Don't adapt two of your own modules to each other; change one of them |
|
||||
| Facade | The `http` client over `fetch`, `XMLHttpRequest`, retry, refresh, and abort; feature actions over repositories, stores, storage, and events | When callers would repeat the same sequence of calls into several parts: one function, or one object with a few verbs. Callers never reach past it: no `fetch` outside the HTTP lib, and no model that repeats an action's steps |
|
||||
| Proxy | Features' `caches/` (React `cache()`); `LocalStorageAdapter`; route guards; lazy widgets | A cache dedupes calls within one request and never outlives it. `LocalStorageAdapter` keeps the `Storage` interface while it namespaces keys and absorbs blocked storage, so it works as a Proxy; keep the name its spec gives it. A guard lets a route through only when its check passes. When lazy loading pays off is in rendering-patterns.md |
|
||||
| Proxy | Features' `caches/` (React `cache()`); `LocalStorageAdapter`; route guards; lazy widgets; the pwa lib's service worker | A cache dedupes calls within one request and never outlives it. The service worker stands in front of the network only for JS, CSS, fonts, and the icon sprite ([lib-pwa.md](lib-pwa.md)). `LocalStorageAdapter` keeps the `Storage` interface while it namespaces keys and absorbs blocked storage, so it works as a Proxy; keep the name its spec gives it. A guard lets a route through only when its check passes. When lazy loading pays off is in rendering-patterns.md |
|
||||
| Decorator | zustand middleware: `immer` and `persist` | When a store needs cross-cutting behavior: wrap the creator and keep its shape, as in `persist(immer(...))` ([code-patterns.md](code-patterns.md#persisted-store)). No TypeScript decorator syntax, and no higher-order components that wrap components (see HOC below) |
|
||||
| Chain of Responsibility | HTTP request and response interceptors; Next.js `proxy.ts`; nested error boundaries | For steps that every request or error passes through. Interceptors run root first and carry only cross-cutting concerns ([lib-http.md](lib-http.md#interceptors)). `proxy.ts` either answers (a redirect) or passes the request on, after it refreshes an expired session. An error stops at the nearest error boundary: part, then page, then app ([error-handling.md](error-handling.md#boundaries)). Never put business logic in a link |
|
||||
| Observer | Action events through `eventEmitter`; zustand selectors; the TanStack Query cache and the queries that observe it | When code must react to a change that its source shouldn't know about. Events fire only after an operation completes. A listener subscribes once in an AppShell effect and unsubscribes in its cleanup, and a component subscribes to the smallest slice. The emitter only broadcasts, so coordination stays in actions and models |
|
||||
|
|
@ -367,7 +367,7 @@ The GoF patterns that the architecture doesn't already use:
|
|||
|
||||
- **Factory Method**: not used in its class form, because nothing here inherits. When a caller needs one of several implementations by key, use a factory function (table above) or a `Record` from key to implementation in the owning module's `constants.ts`. A map of components inside a client component bundles every entry, so heavy entries map to lazy components; a map in a Server Component ships only the client entries it renders (rendering-patterns.md).
|
||||
- **Abstract Factory**: rarely needed, because matching families are already chosen once, higher up: the theme through tokens (Bridge) and the device through the template. Don't build a context that swaps whole component kits; a second brand is a theme in `theme.css`. A real need for different component sets, such as white-label apps, is decided in the plan first.
|
||||
- **Builder**: rarely needed. When a value has many optional parts, such as metadata from `configs/seo.ts` or JSON-LD built from a `*Payload`, write a pure function that takes an options object with defaults and returns the finished value. No chained, mutable builder classes; valibot's `pipe` already composes schemas step by step.
|
||||
- **Builder**: rarely needed. When a value has many optional parts, such as metadata from `configs/seo.ts` or JSON-LD built from a `*Payload` (the json-ld lib's `build*` functions and the platform's `app/json-ld/`, [lib-json-ld.md](lib-json-ld.md)), write a pure function that takes an options object with defaults and returns the finished value. No chained, mutable builder classes; valibot's `pipe` already composes schemas step by step.
|
||||
- **Prototype**: copying is an immutable update: spread for a shallow copy, `structuredClone` for a deep copy of plain data, and immer drafts inside stores. `http.extend` isn't a Prototype: it delegates to the root live instead of copying it, so settings made later in bootstrap still apply ([lib-http.md](lib-http.md#api)). Never `structuredClone` an object that holds functions or class instances; it throws on functions and drops prototypes.
|
||||
- **Template Method**: not used in its class form. Its component form already exists: island templates and organisms such as `PageHeader` fix the layout and take the varying parts as slots. For logic, write a function that owns the sequence and takes the varying steps as callbacks, such as `runImport({ validate, upload, dispatch })`, and move it to `shared/utils/` only when a third feature needs the same sequence.
|
||||
- **Visitor**: rarely needed in app code. To run type-specific logic over mixed nodes, such as CMS content blocks or filter expressions, switch exhaustively over the discriminated union with `assertNever`, or use a `Record` from `type` to handler. A new operation is a new function, and a new node type fails type-check at every switch. No `accept` and `visit` double dispatch.
|
||||
|
|
@ -383,7 +383,7 @@ Keep these out of designs, and flag each one in review with its alternative. A m
|
|||
- **Inheritance between components.** Compose with `children`, slots, cva variants, and compound parts.
|
||||
- **HOCs and mixins in new code.** Use a hook or a wrapper component.
|
||||
- **Events for request and response flows**, such as emitting `cart.totalRequested` and waiting for a reply event. Call the action or repository and await it; events only fan out after an operation completes.
|
||||
- **A second event bus, cache layer, or state library**, such as RxJS subjects, a hand-made fetch cache, Redux, or a context used as a store. Use the event emitter, the query cache (or `cache()` within one server request), and zustand.
|
||||
- **A second event bus, cache layer, or state library**, such as RxJS subjects, a hand-made fetch cache, a service worker that stores pages or data, Redux, or a context used as a store. Use the event emitter, the query cache (or `cache()` within one server request), the pwa lib's worker for JS, CSS, fonts, and the icon sprite only, and zustand.
|
||||
- **A pattern for a future that isn't planned.** Write the direct code, and extract the pattern when the third case arrives (refactoring.md).
|
||||
- **A pattern that needs an upward or cross-product import, or `export *`**, such as an integration that imports a feature to listen to it. Wire it one level up, in the AppShell or the bootstrap, and re-export by name.
|
||||
- **A pattern library without approval**, such as XState or InversifyJS. Use the in-stack alternative first: a discriminated union and a pure reducer in `useReducer` or a zustand store instead of XState, and the bootstrap's `configure` and `setEnv` instead of InversifyJS. Any dependency outside [the stack](../SKILL.md#2-stack) needs a stated reason and approval.
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
|
|||
}
|
||||
```
|
||||
|
||||
**The fallback.** `app/error-boundaries/error-fallback/ErrorFallback.tsx`. `size` is `'app' | 'page' | 'part'`; island's molecules take `'page' | 'part'`.
|
||||
**The fallback.** `app/error-boundaries/error-fallback/ErrorFallback.tsx`. `size` is `'app' | 'page' | 'part'`; island's molecules take `'page' | 'part'`. The outdated fallback needs no branch of its own: `cause` picks its copy, and it gets Reload page like the logic fallback.
|
||||
|
||||
```tsx
|
||||
'use client';
|
||||
|
|
@ -50,18 +50,21 @@ import { classifyError, describeError, handleError } from '@project/libs/error-h
|
|||
import { useEffect, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { StatusEmptyState } from '../status-empty-state';
|
||||
import { reloadOnce } from './reload-once';
|
||||
import type { ErrorFallbackProps } from './types';
|
||||
|
||||
export function ErrorFallback({ error, size, name, onRetry }: ErrorFallbackProps) {
|
||||
const { t } = useTranslation('errors');
|
||||
const headingRef = useRef<HTMLHeadingElement>(null);
|
||||
const { read, cause } = classifyError(error);
|
||||
const { read, cause, retry } = classifyError(error);
|
||||
const islandSize = size === 'part' ? 'part' : 'page';
|
||||
|
||||
useEffect(() => {
|
||||
handleError(error, { where: size, name });
|
||||
// Code from an older deploy: a failed page or app reloads into the current deploy. A part never does.
|
||||
if (retry === 'reload-page' && size !== 'part' && reloadOnce()) return;
|
||||
if (size !== 'part') headingRef.current?.focus();
|
||||
}, [error, size, name]);
|
||||
}, [error, size, name, retry]);
|
||||
|
||||
if (read === 'silent') return null;
|
||||
if (read !== 'boundary') return <StatusEmptyState variant={read} size={islandSize} headingRef={headingRef} />;
|
||||
|
|
@ -86,6 +89,23 @@ export function ErrorFallback({ error, size, name, onRetry }: ErrorFallbackProps
|
|||
}
|
||||
```
|
||||
|
||||
`error-fallback/reload-once.ts`. `constants.ts` holds `OUTDATED_RELOAD_STORAGE_KEY = 'outdated-reload-at'` and `OUTDATED_RELOAD_WINDOW_MS = 60_000`.
|
||||
|
||||
```ts
|
||||
import { storage } from '@project/libs/local-storage';
|
||||
import { OUTDATED_RELOAD_STORAGE_KEY, OUTDATED_RELOAD_WINDOW_MS } from './constants';
|
||||
|
||||
// At most one reload a minute, so a deploy that is still missing files shows the fallback instead of a reload loop.
|
||||
export function reloadOnce(): boolean {
|
||||
if (!navigator.onLine) return false;
|
||||
const last = storage.getJSON<number>(OUTDATED_RELOAD_STORAGE_KEY);
|
||||
if (typeof last === 'number' && Date.now() - last < OUTDATED_RELOAD_WINDOW_MS) return false;
|
||||
storage.setJSON(OUTDATED_RELOAD_STORAGE_KEY, Date.now());
|
||||
window.location.reload();
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
`StatusEmptyState` (`error-boundaries/status-empty-state/`) renders island's `EmptyState` with the `errors:empty.<variant>` copy and, at page size, the link back. It is a client component, so the server page and parts can render it too.
|
||||
|
||||
**Part boundary.** `app/error-boundaries/part-boundary/PartBoundary.tsx`. `PartBoundaryProps` is `{ name: string }`; `catchError` adds `children`.
|
||||
|
|
|
|||
|
|
@ -10,7 +10,8 @@ Contents: The model · What each failure shows · Boundaries · Reads · Actions
|
|||
1) Error boundary ─┬─> Whole app (EB-W)
|
||||
└─> Section (EB-S): a page or a part
|
||||
Fallback types ─┬─> Network: the API or the connection failed; retry helps
|
||||
└─> Logic: a JavaScript bug; retry rarely helps; reported
|
||||
├─> Logic: a JavaScript bug; retry rarely helps; reported
|
||||
└─> Outdated: the page runs code from an older deploy; a page reload fixes it
|
||||
|
||||
2) API error ─┬─> 5xx ─┬─> Read ───> EB-X
|
||||
│ └─> Action ─┐
|
||||
|
|
@ -44,6 +45,7 @@ Contents: The model · What each failure shows · Boundaries · Reads · Actions
|
|||
| 401 | Never reaches the UI: the HTTP lib refreshes, or a failed refresh logs out | Same |
|
||||
| `ABORTED` | Nothing | Nothing |
|
||||
| Logic error (a bug) | EB-X, logic fallback with Reload page and the reference ID; reported | Toast with the support sentence; reported |
|
||||
| A chunk that failed to load (code from an older deploy) | A page or app boundary reloads the page once; a part boundary shows the outdated fallback with Reload page | Toast that the page was updated, with Reload page; the form keeps its values |
|
||||
| Success with no items | ES `no-data`, or `no-results` when filters or a search are active | Not an error |
|
||||
|
||||
- A failed refetch keeps the data on screen and shows nothing. Only a first load that fails reaches a boundary.
|
||||
|
|
@ -61,7 +63,7 @@ Every boundary renders the same `ErrorFallback`, which decides what the user see
|
|||
|
||||
1. It classifies the error. A `silent` read renders nothing: an `ABORTED` request, or a 401 whose logout redirect is already on its way.
|
||||
2. `not-found` and `no-access` render the `StatusEmptyState` at the boundary's size.
|
||||
3. Everything else renders island's `ErrorState`: the network fallback with Try again, or the logic fallback with Reload page. Both show the reference ID when there is one.
|
||||
3. Everything else renders island's `ErrorState`: the network fallback with Try again, or the logic or outdated fallback with Reload page. They show the reference ID when there is one.
|
||||
4. It calls `handleError` once, in an effect, so the error that stopped here is reported once.
|
||||
|
||||
Rules:
|
||||
|
|
@ -71,7 +73,8 @@ Rules:
|
|||
- Retry resets the failed queries first, then the boundary. Otherwise a query that threw keeps its error and throws again at once. There is no provider for this: `useQueryErrorResetBoundary()` returns the global reset.
|
||||
- In a part boundary, an error with a `digest` came from the server, so Try again calls `retry()`. A browser-side error calls `reset()`, which re-renders without a server round trip.
|
||||
- Put `PartBoundary` outside the part's `<Suspense>`, so the fallback replaces the skeleton and the part together. Widgets that load inside a form, such as select options and lazy tabs, get their own `PartBoundary`, so their failure never unmounts the form and loses what the user typed.
|
||||
- `LoadOnVisible` and dynamic imports need nothing extra: a chunk that fails to load throws to the part's boundary ([rendering-patterns.md](rendering-patterns.md#loading-patterns)).
|
||||
- `LoadOnVisible` and dynamic imports need nothing extra: a chunk that fails to load throws to the part's boundary ([rendering-patterns.md](rendering-patterns.md#loading-patterns)), and the error handler classifies it as outdated.
|
||||
- An outdated error at page or app size reloads the page at once, because the page is already gone: at most once a minute, with the time kept in local storage, and only while the browser is online. Otherwise the boundary shows the outdated fallback. A part boundary never reloads on its own, because the user may be typing elsewhere on the page; it offers Reload page. The deploy rules that keep these errors rare are in [b2c-b2b.md](b2c-b2b.md#deploys-and-version-skew).
|
||||
|
||||
## Reads
|
||||
|
||||
|
|
@ -88,7 +91,7 @@ Rules:
|
|||
- `showActionError` is the one error toast: it calls `handleError`, returns early for `silent` errors, and shows `toast.error` with:
|
||||
- the title: what failed, from the caller's `failedMessage`, naming the object ("Category 'Kitchenware' wasn't saved");
|
||||
- the description: the error's message and hint (the guide), or, when there is neither (5xx, unknown, logic), one support sentence with the reference ID;
|
||||
- a button from the retry kind: Try again for `again` when the caller passes `retry`, Reload for `reload` when the caller passes `reload`, and none for `wait`, `fix`, and `none`;
|
||||
- a button from the retry kind: Try again for `again` when the caller passes `retry`, Reload for `reload` when the caller passes `reload`, Reload page for `reload-page`, and none for `wait`, `fix`, and `none`;
|
||||
- `duration: Infinity`, an `id` built from `failedMessage` so a repeated failure replaces its toast instead of stacking, and `testId: 'action-error'`.
|
||||
- `applyServerErrors` puts each server field error under its field and focuses the first, puts field errors for fields the form doesn't render (and whole-submission errors) in the form alert, and then calls `showActionError`. The form keeps every value.
|
||||
- The caller passes `retry` only when running the action again is safe (see What each failure shows). Pass `reload` for actions on data that can change underneath the user (409, 404): it invalidates or refetches the affected queries, and the user tries again on fresh data.
|
||||
|
|
@ -110,7 +113,7 @@ Server reads classify on the server, because a Server Component error reaches th
|
|||
|
||||
- The page reads its main data through `readOnServer`, a server-only helper in the platform's `app/error-boundaries/`. It returns `{ status: 'ok', data }`, or `not-found` for 404 and 410 and `no-access` for 403, and rethrows the rest to the page's `error.tsx`. Server reads send no auth cookies, so only pages that are the same for every visitor read on the server; a page that needs a logged-in user loads in the browser ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
|
||||
- `not-found` calls `notFound()`, which renders the group's `not-found.tsx`. When the page has already started streaming (it has a `loading.tsx`), the status stays 200 and Next.js adds a `noindex` robots tag, which search engines treat as not found.
|
||||
- `no-access` renders the page-size `StatusEmptyState`, and `generateMetadata` returns `robots: { index: false }` for it. `forbidden()` and `unauthorized()` are experimental and not used ([rendering-patterns.md](rendering-patterns.md#rendering-patterns)).
|
||||
- `no-access` renders the page-size `StatusEmptyState`, and `generateMetadata` returns `robots: { index: false }` for it. Like `not-found` and every error page, it renders no JSON-LD ([lib-json-ld.md](lib-json-ld.md#rendering)). `forbidden()` and `unauthorized()` are experimental and not used ([rendering-patterns.md](rendering-patterns.md#rendering-patterns)).
|
||||
- A server part reads through `readOnServer` too: it renders the part-size `StatusEmptyState` for `not-found` and `no-access`, and rethrows the rest to its `PartBoundary`.
|
||||
- A part that must show an empty state awaits its read on the server. An un-awaited prefetch streams its error to the browser as a digest, so use it only for reads that can't answer 404 or 403. `shouldRedactErrors: () => false` in the dehydrate options keeps the real error on the server, so Next.js reports it and the browser gets its digest instead of a generic "redacted" error.
|
||||
- `error.tsx` and `global-error.tsx` render `<meta name="robots" content="noindex" />`, so an error page is never indexed.
|
||||
|
|
@ -126,7 +129,7 @@ Server reads classify on the server, because a Server Component error reaches th
|
|||
## Copy, accessibility, and i18n
|
||||
|
||||
- Every fallback, empty state, and toast says what happened and what the user can do, following the copy rules in [b2c-b2b.md](ui-rules.md#copy). Unknown errors say: "Something went wrong on our side. Try again in a moment. If it keeps happening, contact support and mention reference ID `a1b2c3`."
|
||||
- The `errors` namespace loads on every route, because any route can fail. It holds the HTTP lib's keys (`http.network`, `http.timeout`, their hints, and `http.retry-after`), the support sentences, the fallback copy, the `not-found` and `no-access` copy, and the button labels.
|
||||
- The `errors` namespace loads on every route, because any route can fail. It holds the HTTP lib's keys (`http.network`, `http.timeout`, their hints, and `http.retry-after`), the support sentences, the fallback copy (`network`, `logic`, and `outdated`), the `app.outdated` message, the `not-found` and `no-access` copy, and the button labels.
|
||||
- Server field errors and messages arrive translated; never pass them through `t` again.
|
||||
- Page and app fallbacks move focus to their heading (`tabIndex={-1}`), so keyboard and screen-reader users land on the explanation. Part fallbacks don't take focus and have no live role, so a failed part never interrupts what the user is doing elsewhere.
|
||||
- One `<Toaster>` in the AppShell, with `dir` from the locale and its position on the logical end side (`bottom-right` in LTR, `bottom-left` in RTL).
|
||||
|
|
@ -145,6 +148,7 @@ The boundaries, `ErrorFallback`, `readOnServer`, and the query client's error se
|
|||
[ ] Every failed action shows the action-error toast with its hint or the support sentence and reference ID; the form keeps its values
|
||||
[ ] Server field errors sit under their rendered fields and the rest in the form alert
|
||||
[ ] Retry follows the retry kind: again only when safe, reload for 409 and 404, a wait hint for 429, fix and resubmit for other 4xx
|
||||
[ ] A chunk that failed to load reloads the page once at page or app size, offers Reload page in parts and toasts, and isn't reported
|
||||
[ ] ABORTED and 401 never show anything
|
||||
[ ] Successful empty responses show the no-data or no-results empty state with a next step
|
||||
[ ] handleError runs once per error, where it stops; 5xx and logic errors reach the tracker with requestId or digest
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ Contents: Structure · Types · API · Classification · Messages and reference
|
|||
packages/libs/src/error-handler/
|
||||
├── error-handler.ts # configureErrorHandler, classifyError, describeError, handleError
|
||||
├── types.ts # ErrorClass and its unions, ErrorContext, ErrorReport, ErrorHandlerConfig, TranslateFn, ErrorDescription
|
||||
├── constants.ts # NOT_FOUND_STATUSES, LIB_MESSAGE_PREFIX, RETRY_AFTER_HINT_KEY
|
||||
├── constants.ts # NOT_FOUND_STATUSES, LIB_MESSAGE_PREFIX, RETRY_AFTER_HINT_KEY, OUTDATED_MESSAGE_KEY, CHUNK_ERROR_PATTERN
|
||||
└── index.ts
|
||||
```
|
||||
|
||||
|
|
@ -22,10 +22,10 @@ packages/libs/src/error-handler/
|
|||
## Types
|
||||
|
||||
```ts
|
||||
type ErrorCause = 'network' | 'logic'; // network: the API or the connection failed, retry helps; logic: a bug, retry rarely helps
|
||||
type ErrorCause = 'network' | 'logic' | 'outdated'; // network: the API or the connection failed, retry helps; logic: a bug, retry rarely helps; outdated: the page runs code from an older deploy, a page reload fixes it
|
||||
type ReadOutcome = 'silent' | 'not-found' | 'no-access' | 'boundary'; // what a failed read shows
|
||||
type ActionOutcome = 'silent' | 'toast'; // what a failed action shows
|
||||
type RetryKind = 'again' | 'wait' | 'reload' | 'fix' | 'none';
|
||||
type RetryKind = 'again' | 'wait' | 'reload' | 'reload-page' | 'fix' | 'none';
|
||||
|
||||
interface ErrorClass {
|
||||
cause: ErrorCause;
|
||||
|
|
@ -67,7 +67,7 @@ interface ErrorDescription {
|
|||
## API
|
||||
|
||||
- `configureErrorHandler(config)`: once per module graph, in the app's browser bootstrap (`bootstrap.client.ts`) and in `instrumentation.ts`'s `register()` for the server. It merges `config` into the stored settings, so calling it again is safe. Libs never read env; the bootstrap passes everything in.
|
||||
- `classifyError(error): ErrorClass`: pure. It decides from the status first, then the code (table below). Anything that isn't an `HttpError` is a logic error, except a server error that reached the browser with only its `digest`.
|
||||
- `classifyError(error): ErrorClass`: pure. It decides from the status first, then the code (table below). Anything that isn't an `HttpError` is a logic error, except a chunk that failed to load (outdated) and a server error that reached the browser with only its `digest`.
|
||||
- `describeError(error, t): ErrorDescription`: the words for a toast or a fallback. Only strings that start with `errors:` go through `t`: those are the keys the HTTP lib creates. Server messages and hints arrive translated and pass through as they are.
|
||||
- `handleError(error, context?): ErrorClass`: call it once, where the error stops (the fallback that renders it, the toast that shows it, the refetch that swallows it, or the server's `onRequestError`). It classifies the error, sends a report when `report` is true, runs `onForbidden` on a 403, and returns the class. It never throws: a failing reporter or callback is swallowed, so handling an error never causes a second one.
|
||||
|
||||
|
|
@ -87,16 +87,18 @@ The first matching row wins.
|
|||
| Other 4xx (400, 408, 422, …) | network | boundary | toast | fix | no |
|
||||
| `NETWORK_ERROR`, `TIMEOUT` | network | boundary | toast | again | no |
|
||||
| `PARSE_ERROR`, `INTERCEPTOR_ERROR`, `UNKNOWN` | logic | boundary | toast | none | yes |
|
||||
| Not an `HttpError`: a chunk that failed to load | outdated | boundary | toast | reload-page | no |
|
||||
| Not an `HttpError`, with a `digest` | network | boundary | toast | again | no |
|
||||
| Anything else | logic | boundary | toast | none | yes |
|
||||
|
||||
- 401 never reaches the UI: the HTTP lib refreshes, and a failed refresh logs out ([lib-http.md](lib-http.md#refresh-token)). The server has no refresh and sends no auth cookies, so a server read never expects a 401; `readOnServer` rethrows one to its boundary like any other error ([error-handling.md](error-handling.md#b2cb2b-server)).
|
||||
- A `digest` without `HttpError` fields is a Server Component error seen in the browser: Next.js sends only the digest in production, so the browser can't classify it. The server already classified and reported it, and a retry renders the part again on the server.
|
||||
- Retry kinds: `again` offers a button that runs the same thing again; `wait` offers none and the hint says how long; `reload` offers a button that loads the latest data first; `fix` offers none, because the user must change the input; `none` offers none.
|
||||
- A chunk that failed to load means the page runs code from an older deploy whose file is gone, or the connection dropped while the code loaded. It isn't a bug, so it isn't reported, and a page reload fixes both. The lib matches webpack's `ChunkLoadError` and both bundlers' messages (`CHUNK_ERROR_PATTERN`); check the pattern once against the repo's bundler by deleting a chunk in a production build. Deploy rules that keep it rare: [b2c-b2b.md](b2c-b2b.md#deploys-and-version-skew).
|
||||
- Retry kinds: `again` offers a button that runs the same thing again; `wait` offers none and the hint says how long; `reload` offers a button that loads the latest data first; `reload-page` offers a button that reloads the whole page; `fix` offers none, because the user must change the input; `none` offers none.
|
||||
|
||||
## Messages and reference ID
|
||||
|
||||
- `message` is set for 4xx statuses (the back end localizes them from `Accept-Language`) and for `NETWORK_ERROR` and `TIMEOUT` (the lib's `errors:` keys). It is left out for 5xx and logic errors, whose text means nothing to users and can leak internals.
|
||||
- `message` is set for 4xx statuses (the back end localizes them from `Accept-Language`) and for `NETWORK_ERROR` and `TIMEOUT` (the lib's `errors:` keys). It is left out for 5xx and logic errors, whose text means nothing to users and can leak internals. A chunk that failed to load gets `t('errors:app.outdated')`: the page was updated, and reloading it continues.
|
||||
- `hint` is the error's hint. When there is none and the error has `retryAfter`, it is `t('errors:http.retry-after', { seconds })`.
|
||||
- `referenceId` is `requestId`, or the `digest` when there is no request id. Support finds the report by either.
|
||||
|
||||
|
|
@ -108,11 +110,17 @@ The first matching row wins.
|
|||
|
||||
## Implementation
|
||||
|
||||
`error-handler.ts`, the parts that decide. `constants.ts` holds `NOT_FOUND_STATUSES: readonly number[] = [404, 410]`, `LIB_MESSAGE_PREFIX = 'errors:'`, and `RETRY_AFTER_HINT_KEY = 'errors:http.retry-after'`.
|
||||
`error-handler.ts`, the parts that decide. `constants.ts` holds `NOT_FOUND_STATUSES: readonly number[] = [404, 410]`, `LIB_MESSAGE_PREFIX = 'errors:'`, `RETRY_AFTER_HINT_KEY = 'errors:http.retry-after'`, `OUTDATED_MESSAGE_KEY = 'errors:app.outdated'`, and `CHUNK_ERROR_PATTERN = /Loading (CSS )?chunk .+ failed|Failed to load chunk/`.
|
||||
|
||||
```ts
|
||||
import { isHttpError } from '../http';
|
||||
import { LIB_MESSAGE_PREFIX, NOT_FOUND_STATUSES, RETRY_AFTER_HINT_KEY } from './constants';
|
||||
import {
|
||||
CHUNK_ERROR_PATTERN,
|
||||
LIB_MESSAGE_PREFIX,
|
||||
NOT_FOUND_STATUSES,
|
||||
OUTDATED_MESSAGE_KEY,
|
||||
RETRY_AFTER_HINT_KEY,
|
||||
} from './constants';
|
||||
import type {
|
||||
ErrorClass,
|
||||
ErrorContext,
|
||||
|
|
@ -131,6 +139,7 @@ export function configureErrorHandler(next: ErrorHandlerConfig): void {
|
|||
|
||||
const SILENT: ErrorClass = { cause: 'network', read: 'silent', action: 'silent', retry: 'none', report: false };
|
||||
const LOGIC: ErrorClass = { cause: 'logic', read: 'boundary', action: 'toast', retry: 'none', report: true };
|
||||
const OUTDATED: ErrorClass = { cause: 'outdated', read: 'boundary', action: 'toast', retry: 'reload-page', report: false };
|
||||
|
||||
function apiError(read: ReadOutcome, retry: RetryKind, report = false): ErrorClass {
|
||||
return { cause: 'network', read, action: 'toast', retry, report };
|
||||
|
|
@ -141,8 +150,15 @@ function getDigest(error: unknown): string | undefined {
|
|||
return typeof error.digest === 'string' ? error.digest : undefined;
|
||||
}
|
||||
|
||||
function isChunkLoadError(error: unknown): boolean {
|
||||
return error instanceof Error && (error.name === 'ChunkLoadError' || CHUNK_ERROR_PATTERN.test(error.message));
|
||||
}
|
||||
|
||||
export function classifyError(error: unknown): ErrorClass {
|
||||
if (!isHttpError(error)) return getDigest(error) ? apiError('boundary', 'again') : LOGIC;
|
||||
if (!isHttpError(error)) {
|
||||
if (isChunkLoadError(error)) return OUTDATED;
|
||||
return getDigest(error) ? apiError('boundary', 'again') : LOGIC;
|
||||
}
|
||||
const { status, code } = error;
|
||||
if (code === 'ABORTED' || status === 401) return SILENT;
|
||||
if (status === 403) return apiError('no-access', 'none');
|
||||
|
|
@ -156,7 +172,9 @@ export function classifyError(error: unknown): ErrorClass {
|
|||
}
|
||||
|
||||
export function describeError(error: unknown, t: TranslateFn): ErrorDescription {
|
||||
if (!isHttpError(error)) return { referenceId: getDigest(error) };
|
||||
if (!isHttpError(error)) {
|
||||
return isChunkLoadError(error) ? { message: t(OUTDATED_MESSAGE_KEY) } : { referenceId: getDigest(error) };
|
||||
}
|
||||
const translate = (text?: string) => (text?.startsWith(LIB_MESSAGE_PREFIX) ? t(text) : text);
|
||||
const isUserFacing =
|
||||
(error.status >= 400 && error.status < 500) || error.code === 'NETWORK_ERROR' || error.code === 'TIMEOUT';
|
||||
|
|
@ -230,6 +248,7 @@ For building or changing the lib:
|
|||
[ ] Every row of the classification table returns its class, with status checked before code
|
||||
[ ] ABORTED and 401 are silent for reads and actions; 403 runs onForbidden once per handleError call
|
||||
[ ] A plain Error is a reported logic error; an object with only a digest is a network error that isn't reported
|
||||
[ ] A webpack ChunkLoadError and a Turbopack "Failed to load chunk" error are outdated, retry reload-page, not reported, and describeError gives them the errors:app.outdated message
|
||||
[ ] describeError translates only errors:-prefixed strings; server messages pass through unchanged
|
||||
[ ] describeError leaves out the message for 5xx and logic errors and keeps it for 4xx, network, and timeout
|
||||
[ ] A 429 or 503 with retryAfter and no hint gets the retry-after hint with its seconds
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,492 @@
|
|||
# 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](b2c-b2b.md#no-server-cache)), 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](ui-rules.md#fonts-and-the-icon-sprite)) |
|
||||
| Icon sprite | `/icons/symbol-defs.svg?v=<N>` | Every change raises `ICON_SPRITE_VERSION`, so the URL changes with the content |
|
||||
|
||||
- Same origin and `GET` only. A response is stored only when it has status 200, came from the same origin (`type` is `'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 different `Last-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's `next.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](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.svg` is 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](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.ts` exports `configureServiceWorker`, `registerServiceWorker`, `SERVICE_WORKER_URL`, `SERVICE_WORKER_CONFIG`, and the types `ServiceWorkerOptions` and `ServiceWorkerConfig`. It runs nothing at import, so `bootstrap.client.ts` can import it during SSR. Nothing goes in `server.ts`.
|
||||
- `plugin.ts` exports `writeServiceWorker`, `SERVICE_WORKER_URL`, `SERVICE_WORKER_HEADERS`, and the types `ServiceWorkerPluginOptions` and `CacheStrategy`, on the `@project/libs/pwa/plugin` subpath. 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 no `node:fs`.
|
||||
- `service-worker.ts` runs in the worker's own global scope. It has no `import` or `export`, so the plugin can emit it as one script, and it reads its settings from `SERVICE_WORKER_CONFIG`, which the plugin writes above it. `packages/libs/tsconfig.worker.json` type-checks it with `lib: ["ES2022", "WebWorker"]`. The lib's main tsconfig excludes it, so worker globals such as `clients` never reach the page code's types: the `DOM` and `WebWorker` libs declare the same globals differently.
|
||||
- Import by subpath: `import { registerServiceWorker } from '@project/libs/pwa'`, and in `next.config.ts`, `import { writeServiceWorker } from '@project/libs/pwa/plugin'`.
|
||||
|
||||
## Types
|
||||
|
||||
```ts
|
||||
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, in `bootstrap.client.ts`, with `enabled` from the app's env. It only stores options, so it's safe during SSR. Until it runs, `enabled` is `false`.
|
||||
- `registerServiceWorker()` runs once per page load, in an effect of the platform's `AppShell`. It returns at once and does its work in the background:
|
||||
- With `enabled: true`, it waits for the window's `load` event, so the worker never competes with the page for the network. Then it registers `/sw.js` with scope `/` and `updateViaCache: '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 with `pwa-`. That's the kill switch.
|
||||
- Browsers without service workers, and plain-`http` hosts other than `localhost`, 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".
|
||||
- `writeServiceWorker({ publicDir, strategy })` compiles `service-worker.ts` with the workspace's own `typescript` (`transpileModule`; no new dependency), writes `SERVICE_WORKER_CONFIG` above it with the developer's `strategy` when 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.js` is generated, so git ignores it, like the fonts and the sprite in `public/`.
|
||||
- Add `{projectRoot}/public/sw.js` to the app's build target `outputs`, so an Nx cache hit restores it together with `.next/`. A deploy without it serves a 404 at `/sw.js`.
|
||||
|
||||
## The worker
|
||||
|
||||
- `install`: calls `skipWaiting()`. 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 every `pwa-` cache except the current one, and calls `clients.claim()`, so the open pages use the new worker at once.
|
||||
- `fetch`:
|
||||
- Non-`GET` requests: 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 `fetch` when 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-cached` request whose mode isn't `same-origin` (DevTools sends them) is left alone, because `fetch` rejects it.
|
||||
- `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.js` changes only when this lib changes (its worker code or `SERVICE_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 `v1` in `SERVICE_WORKER_CONFIG.cacheName` whenever 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, so `cacheName` keeps its version.
|
||||
- Kill switch: set `NEXT_PUBLIC_SERVICE_WORKER_ENABLED=false` in 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 build` and `next start`) on `localhost`, which browsers treat as secure.
|
||||
|
||||
## Serving the worker
|
||||
|
||||
- Each app's `next.config.ts` calls `writeServiceWorker` and adds `SERVICE_WORKER_HEADERS` for `/sw.js` to `headers()` (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 honor `no-cache` for 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.js` and `/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 each `useReportWebVitals` metric.
|
||||
- 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.webmanifest` and adds the `<link rel="manifest">`. It exports `dynamic = 'force-dynamic'`, like every metadata route ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
|
||||
- Its fixed fields live in `configs/pwa.ts`: `id: '/'`, which keeps the installed app's identity if `start_url` changes; `start_url: '/'`; `scope: '/'`; `display: 'standalone'`; `background_color`; `theme_color`; and the icons.
|
||||
- `name`, `short_name`, and `description` come 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 set `lang` and `dir` from it.
|
||||
- `background_color` and `theme_color` are the light theme's hex values for the page surface and the brand color in island `theme.css`. The manifest can't read CSS variables, so change both files together. The root layout's `generateViewport` sets `themeColor` for the theme the server chose.
|
||||
- Icons are PNG files in the app's `public/pwa/`: 192×192, 512×512, and a 512×512 `maskable` icon 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`
|
||||
|
||||
```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`
|
||||
|
||||
```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`
|
||||
|
||||
```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.waitUntil` inside `fromNetwork` runs after an `await`. The spec allows it while the event has a pending promise: the `respondWith` promise, or the background check that `staleWhileRevalidate` passes to `waitUntil` first.
|
||||
- `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.
|
||||
|
||||
```ts
|
||||
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](lib-env.md#the-apps-env)).
|
||||
|
||||
```ts
|
||||
// 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`
|
||||
|
||||
```ts
|
||||
configureServiceWorker({ enabled: clientEnv.NEXT_PUBLIC_SERVICE_WORKER_ENABLED });
|
||||
```
|
||||
|
||||
`platforms/<platform>/src/app/app-shell/AppShell.tsx`, beside its other startup effects:
|
||||
|
||||
```tsx
|
||||
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'`.
|
||||
|
||||
```ts
|
||||
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`.
|
||||
|
||||
```ts
|
||||
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.
|
||||
|
||||
```ts
|
||||
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
|
||||
```
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# Page example: caches, page, and parts
|
||||
|
||||
A full page for [b2c-b2b.md](b2c-b2b.md): device detection, caches, a server page loader, the page entrypoint, streamed parts, and query hydration. Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet. Otherwise copy the shape of an existing page.
|
||||
A full page for [b2c-b2b.md](b2c-b2b.md): device detection, caches, a server page loader, the page entrypoint with its JSON-LD, streamed parts, and query hydration. Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet. Otherwise copy the shape of an existing page.
|
||||
|
||||
`platforms/<platform>/src/shared/utils/get-device.ts`
|
||||
|
||||
|
|
@ -45,14 +45,16 @@ export { getProduct, getProductReviews, getRelatedProducts } from './products';
|
|||
```ts
|
||||
import 'server-only';
|
||||
|
||||
export { buildProductPageJsonLd } from './app/json-ld/server';
|
||||
export { getProduct, getProductReviews, getRelatedProducts } from './features/catalog/caches/server';
|
||||
export { getDevice } from './shared/utils/get-device';
|
||||
```
|
||||
|
||||
`apps/<app>/src/app/(shop)/product/[id]/page.tsx`. `generateMetadata` and the page both call `getProduct(id)`, and the cache sends one request. A page whose main read can answer 404 or 403 reads through `readOnServer` instead, as the seller page in [error-handling-code.md](error-handling-code.md) does.
|
||||
`apps/<app>/src/app/(shop)/product/[id]/page.tsx`. `generateMetadata` and the page both call `getProduct(id)`, and the cache sends one request. The page renders its JSON-LD from the same product, beside the template and outside every `<Suspense>`; `buildProductPageJsonLd` is in [lib-json-ld.md](lib-json-ld.md#usage). A page whose main read can answer 404 or 403 reads through `readOnServer` instead, as the seller page in [error-handling-code.md](error-handling-code.md) does, and renders JSON-LD only for an `ok` read.
|
||||
|
||||
```tsx
|
||||
import { getDevice, getProduct } from '@project/<platform>/server';
|
||||
import { JsonLd } from '@project/island/primitives/json-ld/server';
|
||||
import { buildProductPageJsonLd, getDevice, getProduct } from '@project/<platform>/server';
|
||||
import type { Metadata } from 'next';
|
||||
import { ProductDesktop } from './templates/product-desktop';
|
||||
import { ProductMobile } from './templates/product-mobile';
|
||||
|
|
@ -68,7 +70,12 @@ export async function generateMetadata({ params }: ProductPageProps): Promise<Me
|
|||
export default async function ProductPage({ params }: ProductPageProps) {
|
||||
const { id } = await params;
|
||||
const [device, product] = await Promise.all([getDevice(), getProduct(id)]);
|
||||
return device === 'mobile' ? <ProductMobile product={product} /> : <ProductDesktop product={product} />;
|
||||
return (
|
||||
<>
|
||||
<JsonLd data={buildProductPageJsonLd(product)} />
|
||||
{device === 'mobile' ? <ProductMobile product={product} /> : <ProductDesktop product={product} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ apps/<app>/src/
|
|||
├── app/ # Next.js App Router
|
||||
│ ├── global-error.tsx # EB-W: replaces the root layout; own <html> and <body>
|
||||
│ ├── not-found.tsx
|
||||
│ ├── manifest.ts # web app manifest; force-dynamic, default locale (see lib-pwa.md)
|
||||
│ └── (auth)/
|
||||
│ ├── layout.tsx
|
||||
│ ├── loading.tsx
|
||||
|
|
@ -51,8 +52,9 @@ apps/<app>/src/
|
|||
│ ├── app.css # Tailwind entry; imports island.css
|
||||
│ └── index.ts
|
||||
├── configs/
|
||||
│ ├── seo.ts
|
||||
│ ├── seo.ts # metadata defaults and the business facts for JSON-LD (see lib-json-ld.md)
|
||||
│ ├── react-query.ts
|
||||
│ ├── pwa.ts # the manifest's fixed fields: id, start_url, display, colors, icons
|
||||
│ └── index.ts
|
||||
├── constants/
|
||||
│ ├── auth.ts # e.g. the OTP re-send timeout
|
||||
|
|
@ -65,6 +67,7 @@ apps/<app>/src/
|
|||
```
|
||||
|
||||
- Pages are thin entrypoints. A page picks the mobile or the desktop template on the server, so no component branches on viewport size.
|
||||
- `apps/<app>/public/` holds the committed manifest icons in `pwa/` and three generated outputs that git ignores: `fonts/`, `icons/symbol-defs.svg`, and `sw.js` ([lib-pwa.md](lib-pwa.md)).
|
||||
- Every route level may keep its own `organisms/` and `templates/`, shaped like island organisms. They are not routable because they contain no `page.tsx`. They hold only what this route uses; UI that knows a domain and serves several routes or apps lives in the platform's `screens/`.
|
||||
- `styles/`, `configs/`, and `constants/` grow as needed; each keeps an `index.ts`.
|
||||
- The app holds no features, stores, or business logic; those live in `platforms/<platform>/`. Apps never import each other.
|
||||
|
|
@ -87,6 +90,10 @@ platforms/<platform>/src/
|
|||
│ │ ├── error-fallback/ # ErrorFallback: what every boundary renders
|
||||
│ │ ├── status-empty-state/ # the not-found and no-access empty states
|
||||
│ │ └── read-on-server/ # readOnServer; server-only, exported through server.ts
|
||||
│ ├── json-ld/ # one JSON-LD builder per page type; server-only, see lib-json-ld.md
|
||||
│ │ ├── <page-type>-json-ld.ts
|
||||
│ │ ├── constants.ts
|
||||
│ │ └── server.ts # the module's entry; no index.ts
|
||||
│ ├── navigation/
|
||||
│ │ ├── navigation.ts # typed route paths and navigation menus
|
||||
│ │ ├── constants.ts
|
||||
|
|
@ -120,6 +127,8 @@ platforms/<platform>/src/
|
|||
- It is UI: it may import `features/`, `stores/`, `shared/`, the rest of `app/`, island, and integrations. Nothing in `features/`, `stores/`, or `shared/` imports it.
|
||||
- A module that reads caches is server-only, like `read-on-server/`: its entry is `server.ts`, and the platform's `server.ts` re-exports it.
|
||||
|
||||
`json-ld/` holds what each indexable page type tells search engines: pure functions such as `buildProductPageJsonLd(product)`, which turn a feature's `*Payload` and the navigation paths into one graph with the json-ld lib's builders. It sits in `app/` because it needs `navigation/`, which `features/` can't import. It's server-only, and pages render its graph with island's `JsonLd` ([lib-json-ld.md](lib-json-ld.md)).
|
||||
|
||||
## Feature anatomy
|
||||
|
||||
```
|
||||
|
|
@ -206,7 +215,7 @@ packages/island/src/
|
|||
├── organisms/
|
||||
│ └── <component-name>/ # component module + private components/ and hooks/
|
||||
├── templates/ # like organisms
|
||||
├── primitives/ # non-visual structural pieces, e.g. portal, error-boundary; like organisms
|
||||
├── primitives/ # non-visual structural pieces, e.g. portal, error-boundary, json-ld; like organisms
|
||||
├── tools/
|
||||
│ └── <tool-name>/ # e.g. cn, cvx, icon-sprite-plugin, font-copy-plugin, icon-name-extraction
|
||||
│ ├── <tool-name>.ts or <tool-name>.tsx
|
||||
|
|
@ -285,7 +294,7 @@ A piece that knows a domain but is smaller than an organism, such as a price lin
|
|||
|
||||
```
|
||||
packages/libs/src/<lib-name>/ # e.g. http, env, error-handler, cookie, local-storage,
|
||||
├── <lib-name>.ts # custom prototypes, regex, event-emitter
|
||||
├── <lib-name>.ts # pwa, json-ld, custom prototypes, regex, event-emitter
|
||||
├── types.ts
|
||||
├── constants.ts
|
||||
└── index.ts
|
||||
|
|
@ -319,8 +328,10 @@ Fundamental libs have full specs:
|
|||
| `env` | `createClientEnv`; `createServerEnv` (server) | Validating the app's env: public variables on both sides, server variables on the server only | [lib-env.md](lib-env.md) |
|
||||
| `cookie` | `cookie` | Browser cookies for small values the server needs (locale, theme); never tokens | [lib-cookie.md](lib-cookie.md) |
|
||||
| `local-storage` | `storage` | Prefixed, client-only, non-critical data and persisted zustand stores; never tokens or personal data | [lib-local-storage.md](lib-local-storage.md) |
|
||||
| `pwa` | `configureServiceWorker`, `registerServiceWorker`; `writeServiceWorker` (plugin) | The web app manifest's rules and one service worker per app, which stores only JS, CSS, fonts, and the icon sprite | [lib-pwa.md](lib-pwa.md) |
|
||||
| `json-ld` | `configureJsonLd`, `buildGraph`, and `build*` per schema.org type (server) | The schema.org JSON-LD each indexable page renders: the business, the website, products and their offers, policies, breadcrumbs, and stores | [lib-json-ld.md](lib-json-ld.md) |
|
||||
|
||||
`cookie` and `storage` are browser-only and export nothing from `server.ts`; `error-handler` runs on both sides and exports nothing from it either. `http` exports `configureServerHttp` from `server.ts`. `env` exports `createServerEnv` from its own `env/server.ts`, which the project's `server.ts` re-exports.
|
||||
`cookie` and `storage` are browser-only and export nothing from `server.ts`; `error-handler` runs on both sides and exports nothing from it either. `http` exports `configureServerHttp` from `server.ts`. `env` exports `createServerEnv` from its own `env/server.ts`, which the project's `server.ts` re-exports. `pwa` exports nothing from `server.ts`: its page side is browser-only, and its build plugin sits on its own `pwa/plugin` subpath. `json-ld` is server-only: it has only `json-ld/server.ts`, which the project's `server.ts` re-exports.
|
||||
|
||||
## Env flow
|
||||
|
||||
|
|
@ -392,3 +403,4 @@ Workspaces that use `tsconfig.base.json` path aliases instead map `"@project/isl
|
|||
- `sideEffects`: pure TypeScript modules have none. List every file that must run on import, such as CSS and custom prototype extensions; otherwise bundlers drop it.
|
||||
- The root `index.ts` re-exports every module by name, so `@project/island` and `@project/island/atoms/button` expose the same symbols.
|
||||
- A module with its own `server.ts` also gets a `<module>/server` subpath, for example `"./env/server": "./src/env/server.ts"` in libs. The project's `server.ts` re-exports it, so `@project/libs/server` and `@project/libs/env/server` expose the same symbols.
|
||||
- A build-only module gets a `<module>/plugin` subpath, for example `"./pwa/plugin": "./src/pwa/plugin.ts"` in libs. Only build configs such as `next.config.ts` import it, and no root entry re-exports it.
|
||||
|
|
|
|||
|
|
@ -103,7 +103,7 @@ The budgets these patterns protect are in [b2c-b2b.md](b2c-b2b.md#targets). Reco
|
|||
| Route-based splitting | Automatic | The App Router splits each route segment. |
|
||||
| Bundle splitting | Automatic | Steer it with small client boundaries and dynamic imports rather than the bundler's chunk settings, and check each route against its budget. |
|
||||
| Tree shaking | Always | Use named re-exports without `export *`, subpath imports, and `sideEffects` in every package ([project-structure.md](project-structure.md#exports-and-tree-shaking)). |
|
||||
| PRPL | Built in | Preload critical files (next row). Render the route with the streamed server render. Pre-cache only through prefetch, because a service worker is outside the stack and needs approval. Lazy-load the rest with route splitting and dynamic imports. |
|
||||
| PRPL | Built in | Preload critical files (next row). Render the route with the streamed server render. Pre-cache through prefetch, and for repeat visits through the pwa lib's service worker, which keeps JS, CSS, fonts, and the icon sprite and never pages ([lib-pwa.md](lib-pwa.md)). Lazy-load the rest with route splitting and dynamic imports. |
|
||||
| Preload | LCP image, critical font | Preload what [b2c-b2b.md](ui-rules.md#images-fonts-and-css) lists, and use React 19's resource functions for other origins and late files (notes below). |
|
||||
| Prefetch | `next/link` default | Keep `next/link`'s default prefetch (notes below). |
|
||||
| Loading sequence | Always | Load the stylesheet, the critical font, and the LCP image first, then first-party JavaScript, then third parties after hydration. |
|
||||
|
|
|
|||
|
|
@ -30,9 +30,12 @@ const immutable = [{ key: 'Cache-Control', value: 'public, max-age=31536000, imm
|
|||
{ source: '/icons/:path*', headers: immutable },
|
||||
```
|
||||
|
||||
- The pwa lib's service worker keeps them too, by exact URL with the `?v=` included ([lib-pwa.md](lib-pwa.md)). A new sprite version reaches each visitor with their next request, and the worker deletes the old one. A font changed under its old name reaches each visitor one visit late under the default stale-while-revalidate strategy, and long after the change when the developer chose cache first, so a changed font still always gets a new name.
|
||||
|
||||
## SEO and i18n
|
||||
|
||||
- Build `generateMetadata` from `configs/seo.ts`: title, description, canonical URL, `hreflang` alternates, and Open Graph. Add JSON-LD for products, breadcrumbs, and the organization. Provide `sitemap.ts` and `robots.ts`.
|
||||
- Build `generateMetadata` from `configs/seo.ts`: title, description, canonical URL, `hreflang` alternates, and Open Graph. Provide `sitemap.ts`, `robots.ts`, and the web app manifest's `manifest.ts` ([lib-pwa.md](lib-pwa.md#web-app-manifest)).
|
||||
- Every indexable page renders its schema.org JSON-LD with the json-ld lib ([lib-json-ld.md](lib-json-ld.md)): the business and the website on the home page, the product with its offer, rating, and breadcrumb on product pages, the breadcrumb on listing pages, and the store-wide return and shipping policies on their own pages. It says only what the page shows: the same name, price, availability, rating, and trail, in the page's language, with machine values (Latin digits, ISO 8601 dates, ISO 4217 currency).
|
||||
- Server Components translate with a per-request i18next instance from `apps/<app>/src/i18n/`; react-i18next hooks run only in client components. Set `lang` and `dir` on `<html>` from the locale.
|
||||
|
||||
## Copy
|
||||
|
|
@ -77,3 +80,6 @@ Refetches, state updates, and re-renders must never make the UI disappear and re
|
|||
- Tab order follows reading order, Enter submits, and Esc closes. Set sensible default focus and keep primary actions in consistent places.
|
||||
- Preserve context: filters, sort, page, and scroll position survive navigating to a detail page and back. Filters, sort, and page live in the URL, so views are shareable and survive a refresh.
|
||||
- Respect `prefers-reduced-motion` and `prefers-color-scheme`.
|
||||
- Every scroll the page starts is smooth: anchor jumps, `scrollIntoView`, and `scrollTo` animate instead of jumping, so the user sees where they went. island's `island.css` sets `scroll-behavior: smooth` on every element and turns it off under `prefers-reduced-motion` ([code-patterns.md](code-patterns.md#tokens-and-tailwind-wiring)). Code that scrolls never passes `behavior`, so the CSS and the user's motion setting decide.
|
||||
- Every root layout's `<html>` has `data-scroll-behavior="smooth"`. Without it, Next.js 16 animates the jump to the top on every route change.
|
||||
- A scroll container that code holds in place, such as a virtualized list or a chat log pinned to its end, adds `scroll-auto`, or every position fix animates.
|
||||
|
|
|
|||
Loading…
Reference in New Issue