chore: udpate skills

This commit is contained in:
Amiram_se 2026-10-15 14:36:00 +04:00
parent 7075dfe5c1
commit 73eb571530
25 changed files with 23 additions and 7303 deletions

View File

@ -1,28 +1,37 @@
{
"enabledPlugins": {
"nx@nx-claude-plugins": true,
"amiram@amiram-skills": true
},
"extraKnownMarketplaces": {
"nx-claude-plugins": {
"source": {
"source": "github",
"repo": "nrwl/nx-ai-agents-config"
}
},
"amiram-skills": {
"source": {
"source": "git",
"url": "git@github.com:Amiram-sf/skills.git",
"ref": "main"
},
"autoUpdate": true
}
},
"enabledPlugins": {
"nx@nx-claude-plugins": true
},
"sandbox": {
"filesystem": {
"allowRead": [
"/tmp/.nx",
"~/.nx"
],
"allowWrite": [
"network": {
"allowUnixSockets": [
"/tmp/.nx",
"~/.nx"
]
},
"network": {
"allowUnixSockets": [
"filesystem": {
"allowWrite": [
"/tmp/.nx",
"~/.nx"
],
"allowRead": [
"/tmp/.nx",
"~/.nx"
]

View File

@ -1,152 +0,0 @@
---
name: front-end-architect
description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites on Next.js App Router (server rendering, what search engines read, web vitals, bundle and hydration budgets). Applies a fixed architecture (apps, platforms, the island design system, shared libs, DDD features), its stack (Tailwind v4, cva, valibot, react-hook-form, zustand, TanStack Query, i18next, sonner), each project's decision records (ADR, DDR), and one rendering doc per page. Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, SEO, PWA, or Nx projects, when documenting or auditing how a page renders and what crawlers get from it, when planning a feature, when the user states a lasting rule or asks to record or change a decision, or when another skill needs front-end input.
---
# Front-end Architect
Act as a principal front-end architect for Nx monorepos that ship B2C/B2B websites. Design, scaffold, implement, and review front-end code so it stays fast, maintainable, and consistent across projects.
- Explain *why*, not only *what*. Present designs and reviews as checklists.
- When a requirement is ambiguous, state your assumption and continue. Ask only when a wrong guess would be expensive to undo.
- When a request conflicts with a rule here, follow the rule and explain the trade-off, unless an accepted project decision overrides it. When something isn't covered, reason from these principles and say so.
- When `docs/decisions/README.md` exists, read it once per session before any task: each line is one rule, and the project's decisions win. When the user states a lasting rule, or you make a choice that is hard to undo, record it as [references/decisions.md](references/decisions.md) describes.
- Prefer boring, proven technology, fewer re-renders, and the user's time.
## How to read references
The rules below cover most work. References hold the details and are long, so load as little as the task needs:
1. Open a reference only when its row in section 5, What to read, matches the task.
2. Read only the sections the task touches, not the whole file. A link's `#anchor` names one section; otherwise pick them from the file's `Contents:` line (in code-patterns.md, its section table). Find them with `grep -n '^## ' <file>` and read each from its heading to the next.
3. Read a whole reference only when the task covers all of it, such as building the lib it specifies.
## 1. The project
Public websites with 1–20 million visitors a day (Amazon, eBay, Digikala). Apps are thin Next.js App Router apps (`apps/<app>/src/app/`); each product's logic lives in one platform (`platforms/<platform>/`) shared by its apps. Critical: a fresh server render per request with no server cache, web vitals, bundle and chunk size, and hydration and navigation speed.
## 2. Stack
| Concern | Tool | Rule |
|---|---|---|
| Monorepo | Nx | Scaffold with generators (local ones in `tools/` when present), so every component, feature, and repository has the same shape |
| App | Next.js App Router | Server Components by default |
| Styling | Tailwind CSS v4 | Tokens in island `styles/theme.css`; no raw colors or sizes where a token exists |
| Variants | class-variance-authority (cva), clsx, tailwind-merge | cva in each component's `variants.ts`; merge classes with island's `cn` |
| Validation | valibot | Forms, env, and untrusted input. Not Zod |
| Forms | react-hook-form + @hookform/resolvers | `valibotResolver` with schemas from `shared/validations/` |
| Client state | zustand + immer | One store per feature or domain; subscribe through selectors |
| Server state | TanStack Query | `configs/react-query.ts` (confirm the repo uses it first); keys in the repository's `constants.ts`; no query retries, because the HTTP lib retries; a failed first load throws to its boundary |
| Toasts | sonner | After every completed or failed action; never for reads |
| i18n | i18next + react-i18next | No hard-coded UI text |
| Env | @t3-oss/env-core + valibot | Only through `packages/libs/env` |
| Lint and format | oxlint, prettier | ESLint runs module-boundary rules only |
| Scripts and TS configs | jiti | Runs `tools/` scripts and TypeScript configs without a build |
| Icons | svgo | island's `icon-sprite-plugin` writes `symbol-defs.svg` |
| Service worker | Native Service Worker and Cache APIs | Only through the pwa lib. No Workbox or Serwist |
| Structured data | schema.org JSON-LD | Only through the json-ld lib and island's `JsonLd`. No schema-dts or next-seo |
Any dependency outside this stack needs a stated reason and approval.
## 3. Architecture rules
**Naming and exports**
- Files and directories are kebab-case; component files PascalCase (`ProductCard.tsx`); hooks `use-hook-name.ts`. Next.js entry files keep their names (`page.tsx`, `layout.tsx`, `loading.tsx`, `error.tsx`, `not-found.tsx`); route groups are kebab-case: `(auth)`.
- Code lives under `src/`. Every module's `index.ts` re-exports its public API by name (`export { Button } from './Button';`, `export type { ButtonProps } from './types';`), never `export *`. Modules are importable from the project root and their own subpath; code imports by subpath (`@project/island/atoms/button`).
- Every project except apps has `src/server.ts`: it starts with `import 'server-only';`, is the `/server` subpath, holds server-only capabilities, and `index.ts` never imports it. A module with server-only parts has its own `server.ts` beside `index.ts` (the env lib); a server-only module has only `server.ts` (a feature's `caches/`); the project's `server.ts` re-exports them by name.
**Dependency direction**
- apps → platforms → packages. Nothing imports upward, apps never import each other, and no product imports another's app or platform (ESLint with Nx tags).
- island is atomic: atoms → molecules → organisms → templates; no level imports a higher one. `primitives/` (non-visual, such as a portal) sit outside the ladder. An organism's `components/` and `hooks/` are private, except a compound component's named parts.
**Features are DDD** (`features/<feature>/`)
- `entities/`: back-end types, enums, and unions only.
- `http.ts`: `export const catalogHttp = http.extend({ ... })`, imported only by the feature's repositories, not exported. It sets base URL, headers, timeout, retry, and feature interceptors, never refresh or cookie settings; at least `http.extend({})`.
- `repositories/`: request through the feature's client and return data, with no client-side dependencies (hooks, stores, `window`, `cookie`, `storage`), so they run on the server too. Each endpoint has `*Args` (input), `*Dto` (request body), `*ResponseDto` (raw response), and `*Payload` (what apps and stores use); `mappers.ts` converts, and no `*Dto` leaves the repository.
- `caches/` (server-only, entry `server.ts`): React `cache()` wrappers, so each distinct call runs once per request.
- `actions/`: one operation from start to end, for any operation with side effects beyond the request (login: request, store, local storage, follow-up calls, emit `auth.login`, return `'ok'`). Every action emits its event on success unless called with `{ emit: false }`, so other features and integrations react without the action knowing them.
- `models/`: page and part logic as hooks: one page model (`use-login-page.ts`), plus one per part when parts load or change on their own (`use-shipment-address-part.ts`). Pages, templates, and parts stay presentational.
- Beside `features/`: `stores/` (zustand + immer, one per feature or domain, `*Payload` data) and `shared/` (`constants/`, `utils/`, `validations/` with `base-validations.ts` and one `<feature>-validations.ts` each).
**Rendering and data**
- The server render never depends on auth: no session read, no auth cookies, the same HTML for every visitor of a URL. UI that depends on the viewer (needs a logged-in user, differs for guests, members, and paying members, or shows the viewer's data) renders in the browser behind a same-size skeleton that stays until the viewer is known; only the smallest differing piece. Everything else renders on the server. An explicit developer request overrides either default: follow it, state the trade-off, and write it in the plan.
- Every page has a rendering doc, `docs/pages/<app>/<page>.md`, listed in `docs/pages/README.md`: section by section, what each template's server HTML holds for search engines and when each section's JavaScript loads. Read it before you change the page, write it before the code for a new page and link it from the plan, and update it in the same PR as a rendering change ([page-rendering.md](references/page-rendering.md)).
- Client side: repository → model → UI. A `noindex` or blocked page has a skeleton (`loading.tsx`). An indexable page has none, and no `<Suspense>` around `children` above it, so its content is in place in the first flush, and a link to it is the platform's `NavLink`, which shows a pending hint; an entity page (product, category, brand, seller, article, store branch, campaign) also answers a missing entity with a real 404 and a replaced one with a 308 ([b2c-b2b.md](references/b2c-b2b.md#rendering)). Every part that loads on its own has its own `<Suspense>` with a same-size skeleton and part boundary (EB-S).
- Server side: repository → cache → server components. Pages, `generateMetadata`, and server components read only through caches. Client components get server data as props, or through React Query hydration when it must stay live.
- Metadata: fixed values use the `metadata` export, and `generateMetadata` only values that depend on the request or on data (params, locale, a cache read); the same for `viewport` and `generateViewport`. Every app's `next.config.ts` sets `htmlLimitedBots: /.*/`, so metadata is always in `<head>`, never streamed into `<body>`.
- Every root layout's viewport is `width: 'device-width', initialScale: 1, maximumScale: 1`, so iOS doesn't zoom in on a focused input.
- 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.
**Libs** (to use one from a feature, these rules and [code-patterns.md](references/code-patterns.md) are enough)
- Env (`packages/libs/env`): only the app's `env/` files read `process.env`, through `createClientEnv` (public) and `createServerEnv` (server). Other projects use their own `getEnv`, filled by the app's bootstrap; libs get settings through `configure`. Never hard-code an env value (a service or CDN address, key, third-party ID, or flag) as a literal, a fallback (`?? 'http://localhost:3000'`), or a schema default: it comes from the serving app's `.env`, and only apps have `.env` files. Values equal in every environment go in `constants/`.
- HTTP (`packages/libs/http`): one root `http` configured in bootstrap, one `http.extend(...)` per feature, and no `fetch` elsewhere. Cookie auth: on a 401 one refresh runs for the whole app, waiting requests replay once, a failed refresh logs out; the server never refreshes or sends auth cookies. Only idempotent requests retry, with backoff. Every request is abortable; aborts are silent. Uploads report progress. Every failure is an `HttpError` (`{ code, message, status, fieldErrors, hint, requestId, retryAfter }`) that the error handler lib shows and reports.
- `cookie`: browser only, small values the server needs (such as the theme), never tokens (auth cookies are HttpOnly and server-owned), and never the locale or currency of an indexable page, which its URL decides. Server code uses `next/headers`. `storage` (local storage): client-only, non-critical data under the app's prefix and persisted stores, never tokens or personal data. Neither is read during render, at module top level, or in repositories.
- Service worker (`packages/libs/pwa`): one worker per app at `/sw.js`, written by `writeServiceWorker`, registered from the `AppShell` when the app's env turns it on. It stores only `/_next/static/` JS and CSS, `/fonts/` woff2 files, and `/icons/symbol-defs.svg`. Content-hashed JS and CSS (`chunks/`, `css/`, `immutable/`) are cache first, keyed by origin and path without the query string, with no network request on a hit; the rest is stale-while-revalidate by exact URL. Everything else reaches the network untouched; storing another kind needs a recorded decision. `/sw.js` is never renamed or removed; the env flag off unregisters the worker for every visitor.
- PWA: each app is installable from its manifest (`configs/pwa.ts`), with a splash screen on Android (from the manifest) and on iOS (a startup image per device size).
- Structured data (`packages/libs/json-ld`, server only): every indexable page renders one schema.org graph with island's `JsonLd` in its page entry, in the first flush, from its first-paint data: the business (`OnlineStore`) and website on the home page from `configs/seo.ts`, other page types from a builder in the platform's `app/json-ld/`. It says only what the page shows, the same for every visitor: no member or personal price, no rating on the business. `noindex`, not-found, no-access, and error states render none.
**Design system (island)**
- Build UI from island. Never fork or restyle an island component in a feature; add a variant.
- Place a new component in three steps: reuse or add a variant; pick its level by what it renders and imports, never its size; pick its owner by whether it knows a domain.
- Components use semantic tokens (`--color-surface-card`) layered over primitive tokens in `theme.css`, so theming and dark mode need no rewrite.
- Every component defines variants, sizes, states (default, hover, focus-visible, active, disabled, loading, error, selected), and accessibility behavior, with `cursor: pointer` when enabled and `cursor: not-allowed` when disabled built in.
- Fonts and the icon sprite keep fixed names (`yekan-bakh-vf.woff2`, `symbol-defs.svg`) in each app's `public/`, served immutable, never hashed or renamed by any step (not `next/font`). A changed font gets a new name; every sprite change raises `ICON_SPRITE_VERSION` (`?v=<N>`) in the same commit.
- Complex organisms are compound components (`<DataTable.Toolbar>`) that share state through context, with slots or render props for per-entity parts.
**Cross-cutting**
- Components render, models orchestrate, actions run operations, repositories talk to the network, and caches share server reads within a request.
- 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.
- Keep the UI stable: colocate state, split large contexts, never remount a visible subtree on update, and never key dynamic lists by random values or indexes.
- Multi-step flows (wizards, imports, bulk actions) are explicit states (`idle → validating → uploading → processing → done | failed`), never sets of booleans.
- Errors ([error-handling.md](references/error-handling.md)): EB-W at the app root only, a page-size EB-S per page, a part-size EB-S per part that loads on its own. A failed read shows its boundary or empty state (404, 403) and never toasts. A failed action toasts with its hint or 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.
- All text comes from i18next, each a complete description of its purpose ("Save changes to this category", not "Save"). RTL and LTR: `lang` and `dir` from the locale, logical utilities (`ms-*`, `pe-*`, `start-*`), never left and right.
- WCAG 2.1 AA: 4.5:1 text contrast, visible focus rings, full keyboard operation, an `aria-label` on every icon-only button.
## 4. Workflow
For any design or implementation task, write a short plan in the PR description: affected projects and paths; each new component's path, level, and reason; data types; a link to the rendering doc of each new or changed page, and the first-load JS and HTML size of key routes; each rendering override the developer asked for; each new non-obvious pattern.
1. **Clarify the job:** who uses it, how often, and what they finish with it. State assumptions.
2. **Read** the playbook sections the task touches, ui-rules.md for UI work, and the rendering doc of each page the task changes (section 5).
3. **Map the data:** entities, repository types, caches and how each client part gets server data, page and part models, actions and events, query keys, and the query-cache update after each mutation.
4. **Place the code:** list the Nx projects and folders that change; reuse before creating. Give each component its level and owner. For each section of a page, decide what search engines need from it, whether it depends on the viewer, where it renders, and when its code loads, and write it as a row of the page's rendering doc. Add a pattern only for a signal you can name. Refactor code that resists the change first, in its own commit.
5. **Design every state first:** loading, empty (no data, no results, not found, no access), error, in progress, then populated.
6. **Build in layer order** with island components: setup (Nx projects, tags, subpath exports, env variables), foundation (entities, repositories with mappers and query keys, caches, island variants), then each user story (actions, models, templates and organisms, route entry). Fix a bug in the layer that owns it, not in the UI.
7. **Wire feedback:** a toast for every completed action; field errors, a form alert, and an error toast with hint or reference ID and retry for a failed action; a boundary or empty state for a failed read; progress for long operations.
8. **Check performance:** bundle, hydration, web vitals, re-renders, flicker.
9. **Verify and deliver:** `nx affected -t <targets>` for lint, type-check, and tests (target names: `nx show project <name>`). Check the crawler view of each changed page against a production build ([page-rendering.md](references/page-rendering.md#checking-the-crawler-view)). Tick the Definition of Done, and note trade-offs: each new non-obvious pattern with its signal and the simpler option rejected, and smells left as debt.
## 5. What to read
| When the task | Read |
|---|---|
| Designs or writes code | [b2c-b2b.md](references/b2c-b2b.md), the sections it touches |
| Changes what users see or search engines read: a page, template, organism, form, copy, upload, image, font, icon, metadata, or viewport | [ui-rules.md](references/ui-rules.md), the sections it touches |
| Adds an Nx project, a feature, or a top-level folder, or changes tags or exports | [project-structure.md](references/project-structure.md) |
| Adds or moves a component | [project-structure.md#choosing-where-a-component-goes](references/project-structure.md#choosing-where-a-component-goes) |
| Writes a layer: island component, tokens, repository, action, form and model, mutation, store, or env | [code-patterns.md](references/code-patterns.md), that layer's section; or copy an existing file of the same kind |
| Adds a page, part, query, action, or form, or catches or shows an error | [error-handling.md](references/error-handling.md); [error-handling-code.md](references/error-handling-code.md) only to build or change a boundary, `ErrorFallback`, `readOnServer`, or the query client's error settings |
| Adds a page | [page-example.md](references/page-example.md) |
| Adds or moves a part of a page, or changes where it renders or when its code loads | [rendering-patterns.md](references/rendering-patterns.md#choosing-where-a-part-loads), then the sections its steps name |
| Adds a page, or changes a page's sections, where one renders, when its code loads, or what crawlers get; or documents or audits how a page renders | The page's rendering doc in `docs/pages/` first. Then [page-rendering.md](references/page-rendering.md), the sections its intro names for the task, and the page type's section of [page-type-maps.md](references/page-type-maps.md) |
| Shows the current time or the time left, such as a countdown or an open-now badge | [rendering-patterns.md](references/rendering-patterns.md#time-dependent-ui) |
| Adds a pattern or shared abstraction (factory, `Record` map, state machine, adapter, context, generic hook) | [design-patterns.md](references/design-patterns.md) |
| Refactors or reviews code | [refactoring.md](references/refactoring.md): for a review, [Smells that are intended here](references/refactoring.md#smells-that-are-intended-here), [Front-end smells](references/refactoring.md#front-end-smells), and [Review comments](references/refactoring.md#review-comments), plus the catalog row of each smell you name; for a refactor, [When and how](references/refactoring.md#when-and-how) and the technique you use. Also [Not used here](references/design-patterns.md#not-used-here) |
| Builds or changes a lib, or needs lib behavior not described above | [lib-http.md](references/lib-http.md), [lib-error-handler.md](references/lib-error-handler.md), [lib-env.md](references/lib-env.md), [lib-cookie.md](references/lib-cookie.md), [lib-local-storage.md](references/lib-local-storage.md), [lib-pwa.md](references/lib-pwa.md), or [lib-json-ld.md](references/lib-json-ld.md) |
| Touches `/sw.js`, the manifest, splash screens, or what the browser keeps between visits | [lib-pwa.md](references/lib-pwa.md) |
| Adds an indexable page type, or changes what a page tells search engines about the business, a product, its price, or its policies | [lib-json-ld.md](references/lib-json-ld.md): What each page gets, What the markup may say, Values, Rendering, Not in this lib, and the Usage part for that page |
| Records or changes a decision | All of [decisions.md](references/decisions.md): its templates hold `##` lines, so a section read stops early |
| Finishes work, or reviews code or a PR | [definition-of-done.md](references/definition-of-done.md); a review starts at its [Review](references/definition-of-done.md#review) section: every comment names the rule, shows the problem, and proposes the fix |
## 6. Other skills
Before deciding alone outside front-end architecture, check the available skills; when one matches, read its `SKILL.md` and let it lead its area: product and UX design (flows, layouts, hierarchy, token values), system or back-end architecture (service boundaries, API contracts, auth flows), Figma (reading designs), Nx (generators, project graph, running targets), and review, security, and QA (their checks). You own mapping designs onto island, states, feasibility, performance cost, DTO mapping, the pagination, filter, and error contracts the UI needs, project and tag placement, and the rules here.
Hand off with a short brief: context, the decision you need, and this skill's constraints. Asked for front-end input, reply with affected projects and folders, the data flow (repository → action → model → UI), required states, performance concerns, and open questions. With no matching skill, decide and label it an assumption.

View File

@ -1,160 +0,0 @@
# B2C/B2B playbook
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.
Its Definition of Done is in [definition-of-done.md](definition-of-done.md#b2cb2b-additions).
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
## Targets
These are defaults; tighten them per product in the plan.
| Metric | Target |
|---|---|
| LCP, p75 of mobile field data | ≤ 2.5 s |
| INP, p75 | ≤ 200 ms |
| CLS, p75 | ≤ 0.1 |
| TTFB, p75 | ≤ 0.8 s |
| First-load JS per route, gzipped, framework included | ≤ 200 KB |
| Route-specific client JS, gzipped | ≤ 100 KB |
| HTML per template, uncompressed, headers included, on the route's largest page | ≤ 1 MB |
Googlebot reads only the first 2 MB of a page's uncompressed HTML, headers included, and drops the rest. The inline RSC payload repeats most of the page, and streamed parts come last, so they are the first content cut. Cap the items per listing page to stay within the HTML target.
`next build` stopped printing first-load JS in Next.js 16. Measure it and the HTML size as [page-rendering.md](page-rendering.md#checking-the-crawler-view) shows, and record both for key routes in the plan. Any increase on a key route needs a stated reason in the PR.
## No server cache
The Next.js server renders a fresh page for every request and keeps nothing between requests: no prerendered or revalidated pages, and no cached data.
- 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: 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 secondary 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
- Server Components by default. Put `'use client'` only on interactive leaves, never on a layout or page.
- The server render never depends on auth: every visitor of a URL gets the same server HTML. A page or part whose UI depends on the viewer (it needs a logged-in user, differs for guests, members, and paying members, or shows the viewer's own data) renders completely in the browser behind a same-size skeleton. What is the same for every visitor renders on the server. An explicit request from the developer overrides either default ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
- Templates stay Server Components. Interactive parts are small client components, each driven by its part model (`use-<page>-<part>-part.ts`). Don't turn a whole template into a client component to use a page model when only part of it is interactive.
- Keep props passed to client components small and serializable; they are serialized into the page's RSC payload.
- Pages are thin entrypoints. The page resolves the device on the server and renders the mobile or the desktop template, so the markup matches on hydration and nothing shifts. Never choose between layouts with viewport checks in components.
- Choose the template by device class only: `userAgent().device.type === 'mobile'` gets the mobile template, and everything else, tablets included, gets the desktop one. Never branch on `isBot`: content that differs for crawlers is cloaking. Where the repo has a unit test runner, a unit test pins Googlebot Smartphone to the mobile template, because Google indexes that template ([page-example.md](page-example.md)); otherwise propose one, which needs approval ([refactoring.md](refactoring.md#when-and-how)).
- Both templates' client components ship in the route's first-load JavaScript to every device, because the bundler builds a route's chunks from its imports, not from what one request renders. A heavy client component that only one template renders loads through `next/dynamic` in a small client component, so only the device that renders it downloads it.
- The reverse proxy or the CDN adds `Vary: User-Agent` to every HTML response, because one URL serves two templates, and Google's dynamic serving relies on the header. Next.js 16.4 overwrites a `Vary` set in `next.config.ts` or `proxy.ts` on page responses, so the app can't add it.
- Stream: every slow part with secondary content gets `<Suspense>` with a same-size skeleton, inside its own `PartBoundary`, so one slow or failing back-end call never blocks the whole page. Primary content never streams: a slow read it needs is fixed in the back end ([ui-rules.md](ui-rules.md#crawlers)).
- Indexable pages have nothing above them that streams: no `loading.tsx`, and no `<Suspense>` around `children` in a layout or in a component that a layout renders around them, such as the `AppShell` or a provider. React writes a boundary that is complete by the first flush in place only while the HTML of the shell, of the boundaries already in place, and its own stays within 12,800 bytes (its `progressiveChunkSize`, which Next.js doesn't change), or when its own HTML is 500 bytes or less. Above that, it writes the fallback in place and the content after the footer, in a hidden `<div>`, whatever the page awaits. A `loading.tsx` above an indexable page would therefore move its H1, content, and JSON-LD after the footer.
- Entity pages (product, category, brand, seller, article, store branch, campaign) are indexable pages whose URL names one record. With nothing above them that streams, their `generateMetadata` answers a missing entity with a real 404, and a replaced one with a 308, before the first byte ([error-handling.md](error-handling.md#b2cb2b-server)).
- Only `noindex` and blocked pages (search, compare, cart, checkout, account, login) have a `loading.tsx`, so a click shows their skeleton at once. A `loading.tsx` wraps every page below its folder, so put it beside its page, or in a route group that holds only such pages, such as `(account)` or `(auth)`. A link to an indexable page is the platform's `NavLink`, which shows a pending hint instead (Hydration and navigation).
- First flush: on an indexable page, the first byte waits for every read outside a `<Suspense>`, and, with `htmlLimitedBots`, for `generateMetadata`. So the page entry, and every Server Component outside a `<Suspense>`, await only the First flush reads, the reads the page's primary content needs; `generateMetadata` reads the same caches when it needs data, so they share one request. Any other read there holds the status line and the first byte: a secondary section with a read of its own streams in a part inside `<Suspense>`.
- 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, before the template, from the data its first paint already awaits. So structured data is in the first flush and costs no extra request ([lib-json-ld.md](lib-json-ld.md#rendering)).
- Each page's rendering doc records its sections, where each one renders, and when its code loads ([page-rendering.md](page-rendering.md)).
## 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 (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.
- Never call `getEnv`, a repository, or a cache at module top level. Do it inside functions, so bootstrap has always run first.
- Bootstrap code for both sides, env included: [lib-env.md](lib-env.md#usage).
## Data flow
A request becomes a page in this order. The server steps run per request, keep nothing afterwards, and never depend on who the viewer is.
1. Every root layout imports `bootstrap.server.ts` first.
2. The page resolves the device, awaits only the First flush reads (Rendering) through caches or a server page loader, and renders the mobile or the desktop template.
3. Server components that need more data read it through caches. A slow part is an async server component inside `<Suspense>` with a same-size skeleton, so the page streams around it. An auth-dependent part renders only its skeleton on the server.
4. Client components get server data as props or through query hydration (below). In the browser their models take over: queries through repositories, mutations through actions, and auth-dependent parts render their variant once the auth store knows the viewer. After a mutation that changes server-rendered content, `router.refresh()` renders the page again.
**Caches** (`features/<feature>/caches/`, server-only)
- Each cache is React's `cache()` around one repository call: `export const getProduct = cache((id: string) => productsRepository.get({ id }))`. React keeps the result for the current request only, so it's an allowed server cache (see No server cache).
- On the server, pages, loaders, `generateMetadata`, and server components read data only through caches, never through a repository directly. That's why ten components that need the same product send one request.
- Cache arguments are primitives, such as ids and page numbers. React compares arguments by identity, so `getProducts({ page })` would miss every time.
- Define caches at module level. A `cache()` created inside a component is new on every render.
- The module's entry is `server.ts`, with no `index.ts`, and the platform's `server.ts` re-exports it.
**Handing server data to client components**
- Props, for data the client part only shows or starts from: pass the `*Payload`, small and serializable. To stream it, pass the un-awaited promise and read it with `use()` inside `<Suspense>`.
- Query hydration, for data the client part keeps live (refetches, pagination, filters, or mutations that update it): prefetch into a `QueryClient` from `getQueryClient()` in `configs/react-query.ts`, with the cache as the `queryFn`, and render the part inside `<HydrationBoundary state={dehydrate(queryClient)}>`. The part's model queries the same key and starts with the data.
- An awaited prefetch puts the data in the HTML. For a secondary part, wrap the server component in `<Suspense>` so the await streams. A primary section awaits its prefetch outside every `<Suspense>`, from a read the page entry also awaits, so the cache sends one request (Rendering).
- An un-awaited prefetch doesn't block the part: the pending query is dehydrated and streams in, and the model reads it with `useSuspenseQuery`. Page or filter changes then go through `startTransition`, so the part keeps its content instead of falling back to the skeleton.
- A server prefetch calls the cache, never the repository, so a server component that awaits the same data in the same request shares the request.
**Data loaded only in the browser**
- Render on the server what search engines and the first paint need. Load in the browser only what depends on the viewer, is below the fold, or is shown on interaction, through a part model inside `<Suspense>` with a skeleton.
- A browser-only part uses `useQuery` and shows its skeleton while pending, or is loaded with `next/dynamic` from a client component: with `ssr: false` and a same-size `loading` skeleton when it renders at once, and without `ssr: false` when `LoadOnVisible` or an interaction already delays it ([rendering-patterns.md](rendering-patterns.md)). `useSuspenseQuery` is only for queries the server prefetched: any other query would run during SSR, where requests carry none of the user's cookies.
## Errors
The model, the boundaries, and their code are in [error-handling.md](error-handling.md). What is special here:
- Server reads classify on the server, because a Server Component error reaches the browser with only its digest. Pages and server parts read through `readOnServer`. `generateMetadata` and the page call `notFound()` for 404 and 410, which an indexable page answers with a real 404 ([error-handling.md](error-handling.md#b2cb2b-server)). The page renders the `no-access` empty state for 403, with `robots: { index: false }`. A part renders its empty state for 404 and 403. Everything else is rethrown to a boundary.
- Boundaries: `app/global-error.tsx` is EB-W; every route group has `error.tsx` (page EB-S) and, when it calls `notFound()`, `not-found.tsx`; each part has a `PartBoundary` built with `catchError`, which lets `notFound()` and `redirect()` through. Error pages render `noindex`.
- A part that must show an empty state awaits its read on the server; an un-awaited prefetch fits only reads that can't answer 404 or 403.
- `instrumentation.ts` configures the error handler for the server and reports what no server code caught; `bootstrap.client.ts` configures it for the browser.
## State and auth
- `configs/react-query.ts`: `getQueryClient()` returns a new `QueryClient` on every server call and one shared instance in the browser. `staleTime` is above zero (60 s) so hydrated data isn't refetched on mount, queries don't retry (the HTTP lib does), a failed first load throws to its boundary while a failed refetch keeps the data, and pending queries are dehydrated so they can stream.
- zustand stores hold client state only. Never write to a store during server render: on the server a module-level store is shared by every request, so one user's data would leak to another. Pass server data through props or the query cache. If a store must start from server data, create it per request with `createStore` inside a provider.
- Server-side requests forward only the incoming request's cookies that the render needs, such as the theme, and never the auth cookies. Configure the HTTP lib once in `bootstrap.server.ts` with `configureServerHttp`: the server `baseUrl` from the app's server env, and a cookie provider that calls `cookies()` from `next/headers` on each request and keeps only the app's forwarded cookie names ([lib-http.md](lib-http.md#server-side)). That configures the root client, so every feature client forwards the same cookies. Never keep a user's cookies in module state.
- On the server, the HTTP lib never refreshes, never calls `abortAll`, and retries at most once with a shorter timeout, so a slow back end doesn't hold up rendering (see [lib-http.md](lib-http.md#server-side)).
- The server never reads or refreshes the session. The browser learns who the viewer is once per load through the auth store's `status`, and the browser's HTTP lib refreshes an expired session on a 401 ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
- The `cookie` and `storage` libs are browser-only. Never read them during render: client components also render on the server, and the value would differ between server and browser. A value the page needs while rendering, such as the theme, is read on the server with `cookies()` and passed down as a prop. On an indexable page, the URL decides the locale and the currency, never a cookie ([ui-rules.md](ui-rules.md#crawlers)).
- Persisted zustand stores set `skipHydration: true` and rehydrate in an effect of the platform's `AppShell`, so the first browser render matches the server's (code in code-patterns.md, Persisted store).
## Bundle and code splitting
- Import island, libs, and every other package by subpath (`@project/island/atoms/button`), never from a root barrel.
- Declare `sideEffects` in every package so unused modules are dropped.
- Load heavy client-only widgets (maps, charts, rich editors, galleries, video players, chat) with `next/dynamic` inside a client component, on interaction or when visible, with a same-size skeleton.
- Load third-party scripts from `packages/integrations` after hydration (`next/script` with `afterInteractive` or `lazyOnload`), never in the critical path.
- Check a dependency's gzipped size before adding it, and prefer what the stack already has.
- Load only the active locale and the namespaces the route uses.
## Hydration and navigation
- Render output must be identical on server and client: no `Date.now()`, `new Date()`, `Math.random()`, `typeof window` branches, or locale and time-zone differences in render. Format numbers with the locale the server chose. Format absolute dates on the server for everything the server renders, with every option pinned, and pass the text down; a browser-only part formats its own with `formatDateTime`. UI that shows the current time reads the shared clock ([rendering-patterns.md](rendering-patterns.md#time-dependent-ui)).
- Fewer and smaller client boundaries hydrate faster.
- Navigate with `next/link` so routes prefetch. Keep the header and footer in layouts, so navigation re-renders only the page segment. Indexable pages have no `loading.tsx`, so a link to one prefetches nothing, and the current page stays until the new one arrives: every link to an indexable page is the platform's `NavLink`, which shows a pending hint inside the clicked link ([rendering-patterns.md](rendering-patterns.md#loading-patterns)).
- 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), 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
In [page-example.md](page-example.md). Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet.

View File

@ -1,649 +0,0 @@
# Code patterns
Reference implementations for each layer. Paths are relative to the project that owns the code: `platforms/<platform>/src/` for a product's logic and `packages/<name>/src/` for shared packages. `@project` is the workspace scope. The `@project/libs/*` APIs shown follow the lib specs: `http` and `isHttpError` in [lib-http.md](lib-http.md), the error handler's functions in [lib-error-handler.md](lib-error-handler.md), `storage` in [lib-local-storage.md](lib-local-storage.md), `cookie` in [lib-cookie.md](lib-cookie.md). `eventEmitter` stands for the repo's own lib; match its real signature.
Caches, the page entrypoint, and server-to-client data live in [b2c-b2b.md](b2c-b2b.md).
This file is the house code for each layer. Which design pattern to use, when, and where it lives is in [design-patterns.md](design-patterns.md). Error boundaries, fallbacks, empty states, and the query client's error settings are in [error-handling.md](error-handling.md), and their code in [error-handling-code.md](error-handling-code.md).
Read only the section you need:
| You are writing | Section |
|---|---|
| An island component or a variant | [Island component module](#island-component-module) |
| Tokens, or a project's Tailwind sources | [Tokens and Tailwind wiring](#tokens-and-tailwind-wiring) |
| A repository, its types, mapper, or query keys | [Repository](#repository) |
| An action and its event | [Action](#action) |
| A form, a page or part model, or server errors on a form | [Validation, model, and server errors](#validation-model-and-server-errors) |
| A mutation and its cache update | [Mutation with a valid cache](#mutation-with-a-valid-cache) |
| A store | [Store](#store), and [Persisted store](#persisted-store) when it survives a reload |
| A project's env | [Env](#env) |
## Island component module
`atoms/button/variants.ts`
```ts
import { cva } from 'class-variance-authority';
export const buttonVariants = cva(
'inline-flex cursor-pointer items-center justify-center gap-2 rounded-md font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-action-primary disabled:cursor-not-allowed disabled:opacity-50',
{
variants: {
variant: {
primary: 'bg-action-primary text-on-action hover:bg-action-primary-hover',
secondary: 'border border-border-subtle bg-surface-card text-text-primary hover:bg-surface-muted',
danger: 'bg-status-danger text-on-action hover:bg-status-danger-hover',
},
size: {
sm: 'h-8 px-3 text-sm',
md: 'h-10 px-4 text-sm',
lg: 'h-11 px-5 text-base',
},
},
defaultVariants: { variant: 'primary', size: 'md' },
},
);
```
`atoms/button/types.ts`
```ts
import type { VariantProps } from 'class-variance-authority';
import type { ComponentPropsWithRef } from 'react';
import type { buttonVariants } from './variants';
export type ButtonProps = ComponentPropsWithRef<'button'> &
VariantProps<typeof buttonVariants> & {
isLoading?: boolean;
};
```
`atoms/button/Button.tsx`
```tsx
import { cn } from '../../tools/cn';
import { Spinner } from '../spinner';
import type { ButtonProps } from './types';
import { buttonVariants } from './variants';
export function Button({
className,
variant,
size,
isLoading = false,
disabled,
type = 'button',
children,
...props
}: ButtonProps) {
return (
<button
type={type}
className={cn(buttonVariants({ variant, size }), className)}
disabled={disabled || isLoading}
aria-busy={isLoading || undefined}
{...props}
>
{isLoading && <Spinner size="sm" />}
{children}
</button>
);
}
```
`atoms/button/index.ts`
```ts
export { Button } from './Button';
export type { ButtonProps } from './types';
export { buttonVariants } from './variants';
```
`tools/cn/cn.ts`
```ts
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
```
tailwind-merge doesn't know the theme. If `theme.css` adds a token it can't classify, such as a font size `text-body-sm` (which it reads as a color and drops next to `text-text-primary`), build `cn` with `extendTailwindMerge` and register the token.
## Tokens and Tailwind wiring
`styles/theme.css`: primitives are plain theme values, semantic tokens point at primitives and switch per theme, and `@theme inline` turns the semantic tokens into utilities (`bg-surface-card`, `text-text-muted`). Components use only the semantic utilities, so they never need `dark:` variants.
```css
@theme {
--color-neutral-0: #ffffff;
--color-neutral-50: #f4f6fa;
--color-neutral-900: #161b23;
--color-neutral-950: #0f1319;
--color-blue-500: #3b82f6;
--color-blue-600: #2563eb;
}
:root {
--surface-page: var(--color-neutral-50);
--surface-card: var(--color-neutral-0);
--action-primary: var(--color-blue-600);
}
.dark {
--surface-page: var(--color-neutral-950);
--surface-card: var(--color-neutral-900);
--action-primary: var(--color-blue-500);
}
@theme inline {
--color-surface-page: var(--surface-page);
--color-surface-card: var(--surface-card);
--color-action-primary: var(--action-primary);
}
```
This is an excerpt. The real file defines every semantic token the components use, such as `text-primary`, `text-muted`, `border-subtle`, `on-action`, the `status-*` colors, and their hover states.
`styles/island.css`
```css
@import './theme.css';
@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`.
```css
@font-face {
font-family: 'Yekan Bakh';
src: url('/fonts/yekan-bakh-vf.woff2') format('woff2');
font-weight: 100 900;
font-display: swap;
}
@font-face {
font-family: 'Yekan Bakh Fallback';
src: local('Tahoma');
size-adjust: 102%;
ascent-override: 95%;
descent-override: 28%;
line-gap-override: 0%;
}
```
`apps/<app>/src/styles/app.css`
```css
@import 'tailwindcss' source('../');
@import '@project/island/styles/island.css';
@source '../../../../platforms/<platform>/src';
```
Tailwind generates only the classes it finds in registered sources. island registers itself in `island.css`; the app registers its own `src/`, its platform, and any integration that renders UI. CSS `@import` resolves package names through package.json `exports`, not TypeScript path aliases, so path-alias workspaces import `island.css` by relative path.
## Repository
`features/auth/entities/user/types.ts`
```ts
export type UserRole = 'customer' | 'seller';
export type User = {
id: string;
full_name: string;
role: UserRole;
};
```
`features/auth/repositories/auth/types.ts`
```ts
import type { User, UserRole } from '../../entities/user';
export type LoginArgs = { phone: string; password: string };
export type LoginDto = { mobile: string; password: string };
export type LoginResponseDto = { user: User; is_first_login: boolean };
export type LoginPayload = {
user: { id: string; fullName: string; role: UserRole };
isFirstLogin: boolean;
};
```
`features/auth/repositories/auth/mappers.ts`
```ts
import type { LoginArgs, LoginDto, LoginPayload, LoginResponseDto } from './types';
export function toLoginDto(args: LoginArgs): LoginDto {
return { mobile: args.phone, password: args.password };
}
export function toLoginPayload(dto: LoginResponseDto): LoginPayload {
return {
user: { id: dto.user.id, fullName: dto.user.full_name, role: dto.user.role },
isFirstLogin: dto.is_first_login,
};
}
```
`features/auth/repositories/auth/constants.ts`
```ts
export const AUTH_ENDPOINTS = {
login: '/auth/login',
logout: '/auth/logout',
refresh: '/auth/refresh',
} as const;
```
`features/auth/http.ts`. Every feature has one; this feature needs nothing special, so it only extends the root. A feature with its own service sets `baseUrl`, headers, timeout, or retry here (see [lib-http.md](lib-http.md#root-and-feature-clients)).
```ts
import { http } from '@project/libs/http';
export const authHttp = http.extend({});
```
`features/auth/repositories/auth/auth.ts`. Repositories send requests only through their feature's client and never through the root `http`. Login sends `skipRefresh: true`: the back end answers wrong credentials with 400 or 422 and field errors, so a 401 always means "no valid session" and never starts a refresh ([error-handling.md](error-handling.md#actions)).
```ts
import { authHttp } from '../../http';
import { AUTH_ENDPOINTS } from './constants';
import { toLoginDto, toLoginPayload } from './mappers';
import type { LoginArgs, LoginPayload, LoginResponseDto } from './types';
export const authRepository = {
async login(args: LoginArgs): Promise<LoginPayload> {
const response = await authHttp.post<LoginResponseDto>(AUTH_ENDPOINTS.login, toLoginDto(args), {
skipRefresh: true,
});
return toLoginPayload(response);
},
};
```
Read methods take an optional last parameter `{ signal?: AbortSignal }` and forward it, so TanStack Query can cancel them (see Mutation with a valid cache).
`features/auth/repositories/auth/index.ts` exports no `*Dto`:
```ts
export { authRepository } from './auth';
export { AUTH_ENDPOINTS } from './constants';
export type { LoginArgs, LoginPayload } from './types';
```
Query keys sit in the repository's `constants.ts`, start with the domain, and are hierarchical so invalidation is precise. `features/catalog/repositories/products/constants.ts`:
```ts
import type { ListProductsArgs } from './types';
export const PRODUCTS_ENDPOINT = '/catalog/products';
export const productKeys = {
all: ['catalog', 'products'] as const,
lists: () => [...productKeys.all, 'list'] as const,
list: (args: ListProductsArgs) => [...productKeys.lists(), args] as const,
details: () => [...productKeys.all, 'detail'] as const,
detail: (id: string) => [...productKeys.details(), id] as const,
};
```
## Action
`features/auth/constants.ts`. Event names are `<feature>.<action>`.
```ts
export const AUTH_EVENTS = {
login: 'auth.login',
logout: 'auth.logout',
} as const;
export const LAST_PHONE_STORAGE_KEY = 'last-phone';
```
`features/auth/actions/login/actions.ts`. The repository throws the normalized `HttpError` when the request fails, so reaching the next line means the response was successful. The caller handles the error.
```ts
import { eventEmitter } from '@project/libs/event-emitter';
import { storage } from '@project/libs/local-storage';
import { useAuthStore } from '../../../../stores/auth';
import { AUTH_EVENTS, LAST_PHONE_STORAGE_KEY } from '../../constants';
import { authRepository, type LoginArgs } from '../../repositories/auth';
export async function login(args: LoginArgs, { emit = true }: { emit?: boolean } = {}): Promise<'ok'> {
const { user, isFirstLogin } = await authRepository.login(args);
useAuthStore.getState().setSession({ user, isFirstLogin });
storage.setItem(LAST_PHONE_STORAGE_KEY, args.phone);
if (emit) eventEmitter.emit(AUTH_EVENTS.login, { userId: user.id });
return 'ok';
}
```
- Every action emits its event as its last step, so a failed step throws before the emit and listeners only hear about completed operations.
- `{ emit: false }` is for callers that must not trigger listeners, such as an action that runs another action as one of its steps and emits its own event.
- Code that reacts to an action (analytics, another feature's refresh) subscribes to its event instead of being called from the action. Subscribe once, in an effect of the `AppShell`, and unsubscribe in its cleanup.
## Validation, model, and server errors
`shared/validations/base-validations.ts`. Messages are i18n keys; the field component translates them. Each message tells the user how to fix the value, for example "Enter an 11-digit mobile number that starts with 09."
```ts
import { MOBILE_REGEX } from '@project/libs/regex';
import * as v from 'valibot';
export const requiredString = (message: string) => v.pipe(v.string(), v.trim(), v.nonEmpty(message));
export const mobileNumber = (message: string) =>
v.pipe(v.string(), v.trim(), v.regex(MOBILE_REGEX, message));
```
`shared/validations/auth-validations.ts`
```ts
import * as v from 'valibot';
import { mobileNumber, requiredString } from './base-validations';
export const loginSchema = v.object({
phone: mobileNumber('validation:phone.invalid'),
password: requiredString('validation:password.required'),
});
```
`shared/validations/types.ts`
```ts
import type * as v from 'valibot';
import type { loginSchema } from './auth-validations';
export type LoginFormValues = v.InferOutput<typeof loginSchema>;
```
`shared/utils/show-action-error.ts`: the one error toast for a failed action ([error-handling.md](error-handling.md#actions)). It handles the error once, says what failed, adds the hint or a support sentence with the reference ID, and offers the button its retry kind allows.
```ts
import { describeError, handleError, type TranslateFn } from '@project/libs/error-handler';
import { toast } from 'sonner';
export type ShowActionErrorOptions = {
t: TranslateFn;
failedMessage: string; // what failed, naming the object: "Category 'Kitchenware' wasn't saved"
retry?: () => void; // only when running the action again is safe
reload?: () => void; // refetches the data the action changed, for 409 and 404
};
export function showActionError(error: unknown, { t, failedMessage, retry, reload }: ShowActionErrorOptions): void {
const errorClass = handleError(error, { where: 'action' });
if (errorClass.action === 'silent') return;
const { message, hint, referenceId } = describeError(error, t);
const details = [message, hint].filter(Boolean).join(' ');
const button =
errorClass.retry === 'again' && retry
? { label: t('errors:action.try-again'), onClick: retry }
: errorClass.retry === 'reload' && reload
? { label: t('errors:action.reload'), onClick: reload }
: errorClass.retry === 'reload-page'
? { label: t('errors:action.reload-page'), onClick: () => window.location.reload() }
: undefined;
toast.error(failedMessage, {
id: `action-error:${failedMessage}`,
description:
details || t(referenceId ? 'errors:support.with-reference' : 'errors:support.without-reference', { referenceId }),
duration: Infinity,
testId: 'action-error',
action: button,
});
}
```
`shared/utils/apply-server-errors.ts`: field errors go under the fields the form renders (the first one gets focus), field errors for fields it doesn't render and errors about the whole submission go to the form-level alert, and `showActionError` shows the toast. A field counts as rendered when it has a value, so every form sets `defaultValues` for every field.
```ts
import { classifyError, describeError } from '@project/libs/error-handler';
import { isHttpError } from '@project/libs/http';
import type { FieldValues, Path, UseFormReturn } from 'react-hook-form';
import { showActionError, type ShowActionErrorOptions } from './show-action-error';
export function applyServerErrors<T extends FieldValues>(
form: UseFormReturn<T>,
error: unknown,
options: ShowActionErrorOptions,
): void {
if (classifyError(error).action === 'silent') return;
const unmatched: string[] = [];
let hasFieldError = false;
for (const [field, message] of Object.entries(isHttpError(error) ? (error.fieldErrors ?? {}) : {})) {
if (form.getValues(field as Path<T>) === undefined) {
unmatched.push(message);
continue;
}
form.setError(field as Path<T>, { type: 'server', message }, { shouldFocus: !hasFieldError });
hasFieldError = true;
}
if (!hasFieldError && unmatched.length === 0) {
unmatched.push(describeError(error, options.t).message ?? options.failedMessage);
}
if (unmatched.length > 0) form.setError('root.server', { type: 'server', message: unmatched.join(' ') });
showActionError(error, options);
}
```
- Server field messages arrive translated; they are never passed through `t` again. The lib's own `errors:` keys are translated by `describeError`.
- The form keeps every value, so after a 5xx or a network error the user submits again, and after a 4xx they fix the field and resubmit.
`features/auth/models/login/use-login-page.ts`
```ts
import { valibotResolver } from '@hookform/resolvers/valibot';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { applyServerErrors } from '../../../../shared/utils';
import { loginSchema, type LoginFormValues } from '../../../../shared/validations';
import { login } from '../../actions/login';
export function useLoginPage() {
const { t } = useTranslation('auth');
const router = useRouter();
const form = useForm<LoginFormValues>({
resolver: valibotResolver(loginSchema),
mode: 'onTouched',
defaultValues: { phone: '', password: '' },
});
const submit = form.handleSubmit(async (values) => {
try {
await login(values);
toast.success(t('login.success'));
router.push('/');
} catch (error) {
applyServerErrors(form, error, { t, failedMessage: t('login.failed') });
}
});
return { form, submit, isSubmitting: form.formState.isSubmitting };
}
```
`mode: 'onTouched'` validates a field on its first blur and on every change after that. The submit button is disabled only while `isSubmitting`, never because the form is invalid, so users can click it to find out what is wrong. Login passes no `retry`: submitting again is the retry, and sending credentials twice from a toast would surprise the user.
## Mutation with a valid cache
After every create, update, or delete, set the detail, patch the affected lists, then invalidate the lists to reconcile in the background. When patching isn't practical, invalidate every key that can contain the entity (details, lists, counts, dashboards). Never rely on `staleTime` expiring.
Use optimistic updates only for quick toggles (active/inactive, favorite), always with a rollback in `onError` and `showActionError` explaining the failure.
The query needs no error branch: a failed first load throws to the part's boundary, and a failed refetch keeps the data ([error-handling.md](error-handling.md#reads)). The mutation's `onError` shows the toast. Updating a product is a PUT, so running it again is safe and the toast offers Try again with the same input.
`features/catalog/models/product-edit/use-product-edit-page.ts`
```ts
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { showActionError } from '../../../../shared/utils';
import { productKeys, productsRepository, type ProductsPagePayload } from '../../repositories/products';
export function useProductEditPage(productId: string) {
const { t } = useTranslation('catalog');
const queryClient = useQueryClient();
const product = useQuery({
queryKey: productKeys.detail(productId),
queryFn: ({ signal }) => productsRepository.get({ id: productId }, { signal }),
});
const save = useMutation({
mutationFn: productsRepository.update,
onSuccess: (updated) => {
queryClient.setQueryData(productKeys.detail(updated.id), updated);
queryClient.setQueriesData<ProductsPagePayload>({ queryKey: productKeys.lists() }, (page) =>
page ? { ...page, items: page.items.map((item) => (item.id === updated.id ? updated : item)) } : page,
);
void queryClient.invalidateQueries({ queryKey: productKeys.lists() });
toast.success(t('product.saved', { name: updated.name }));
},
onError: (error, args) =>
showActionError(error, {
t,
failedMessage: t('product.saveFailed', { name: args.name }),
retry: () => {
save.mutate(args);
},
reload: () => {
void queryClient.invalidateQueries({ queryKey: productKeys.detail(productId) });
},
}),
});
return { product, save };
}
```
A form that saves through the mutation awaits `mutateAsync` inside `form.handleSubmit` and calls `applyServerErrors` in its `catch` ([design-patterns.md](design-patterns.md#patterns-the-architecture-already-uses)). Leave `onError` out then, so the toast shows once.
## Store
`stores/auth/types.ts`
```ts
import type { LoginPayload } from '../../features/auth';
export type Session = {
user: LoginPayload['user'];
isFirstLogin: boolean;
};
export type ViewerStatus = 'unknown' | 'guest' | 'member';
export type AuthState = {
status: ViewerStatus;
session: Session | null;
setSession: (session: Session) => void;
clearSession: () => void;
};
```
`stores/auth/auth-store.ts`. Components subscribe to the smallest slice they render, never to the whole store.
```ts
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import type { AuthState } from './types';
export const useAuthStore = create<AuthState>()(
immer((set) => ({
status: 'unknown',
session: null,
setSession: (session) =>
set((state) => {
state.status = 'member';
state.session = session;
}),
clearSession: () =>
set((state) => {
state.status = 'guest';
state.session = null;
}),
})),
);
export const useCurrentUser = () => useAuthStore((state) => state.session?.user);
export const useViewerStatus = () => useAuthStore((state) => state.status);
```
Never write to a store during server render (see b2c-b2b.md).
- `status` stays `'unknown'` on the server and in the first browser render, so auth-dependent parts render their skeleton until the browser knows the viewer, and `'unknown'` never reads as a guest.
- The `AppShell` calls the auth feature's `restoreSession` action once in an effect. It reads the session through the auth repository and calls `setSession` or `clearSession` ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
## Persisted store
A store that survives a reload keeps its data in local storage through the `storage` adapter, so the key lands under the app's prefix (`shop.session.cart`). `stores/cart/cart-store.ts`:
```ts
import { storage } from '@project/libs/local-storage';
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type { CartState } from './types';
export const useCartStore = create<CartState>()(
persist(
immer((set) => ({
items: [],
addItem: (item) =>
set((state) => {
state.items.push(item);
}),
clear: () =>
set((state) => {
state.items = [];
}),
})),
{
name: 'session.cart',
storage: createJSONStorage(() => storage),
version: 1,
partialize: (state) => ({ items: state.items }),
skipHydration: true,
},
),
);
```
- `name` is the key. `session.` marks it as the logged-in user's data, so logout's `storage.clearByPrefix('session.')` removes it.
- `partialize` persists only what must survive a reload. Bump `version` and add `migrate` when the shape changes.
- Keep `skipHydration: true` and rehydrate after mount, so the server render and the first browser render match. In the platform's `AppShell`: `useEffect(() => { void useCartStore.persist.rehydrate(); }, []);`.
## Env
The app's `env/` files, a project's `setEnv` and `getEnv`, and both bootstraps: [lib-env.md](lib-env.md#usage).

View File

@ -1,81 +0,0 @@
# Decisions
How to keep a project's architecture decision records (ADR) and design decision records (DDR) in one log, so a decision made once is followed in every later task. Read this file only when you add, accept, reject, or supersede a decision. To follow decisions, the index is enough ([SKILL.md](../SKILL.md)).
Contents: Layout · When to record · Writing a record · Changing a decision · Precedence
## Layout
`docs/decisions/` at the monorepo root holds one file per decision and one index. Create both with the first decision.
```
docs/decisions/
README.md # the index
0001-zod-instead-of-valibot.md
0002-island-components-over-native-elements.md
```
The index lists only live decisions, one line each. The line is the rule itself, one imperative sentence with its scope, so a task follows it without opening the record. Open a record only to change it, or when a case isn't clear from its line.
```markdown
# Decisions
## Design (DDR)
- 0002 Build UI with island components; never use native interactive elements (`button`, `input`, `select`, `textarea`, `a`) in features or apps.
## Architecture (ADR)
- 0001 Validate with Zod instead of valibot in every project.
## Proposed
- 0003 architecture: Load the reviews part only on interaction, on every product page.
```
- The area is where the rule applies: design for UI, island, tokens, copy, and UX; architecture for everything else.
- Keep a line under about 30 words. A rule that needs more is two decisions, or its detail belongs in the record.
- Rejected and superseded decisions leave the index. Their files stay, with their status, as history.
## When to record
- The user states a lasting rule for the project: "always", "never", "use X instead of Y", "from now on". Write it as `Accepted`, because the user decides, and say so in one line: "Recorded as decision 0004."
- You make a choice that is hard to undo, adds a dependency, deviates from this skill, or sets a pattern beyond the current task. Write it as `Proposed` and list it in the PR's plan. It binds nothing until the user accepts it.
Don't record a one-off instruction for the current task, a rule this skill already states, or detail that one file shows. When you can't tell whether an instruction is lasting, follow it for the task and ask in your final message whether to record it.
Before you propose a decision, search `docs/decisions/` for its topic, so you don't propose again what the user rejected or superseded.
## Writing a record
Number: the highest number in the folder plus 1, four digits. File name: `NNNN-<kebab-title>.md`. Keep a record under about 25 lines.
```markdown
# 0002 Island components over native elements
Status: Accepted · Area: design · Date: 2026-10-04 · Decided by: user
## Context
Why the decision came up, in one to three sentences.
## Decision
The rule in the imperative, with its scope and exceptions.
## Alternatives
- The option, and why it lost. "Not discussed" when the user gave none.
## Consequences
What becomes easier or harder, and which existing code doesn't follow it yet.
```
- `Decided by` is `user` or `agent`. Add `Supersedes: NNNN` to the status line when it applies.
- Add the record's line to its area in the index, or to Proposed.
- Existing code that breaks a new decision is debt. List it under Consequences, and fix it only when the user asks or a task touches that code.
## Changing a decision
- Accept: set `Status: Accepted`, and move the line from Proposed to its area.
- Reject: set `Status: Rejected`, add the reason in one line under Decision, and remove the line from the index.
- Supersede: never rewrite the body of an accepted record. Write a new record with `Supersedes: NNNN`, set the old one to `Status: Superseded by MMMM`, and replace the old index line with the new one. A typo fix or clearer wording that keeps the rule is fine in place.
- When the user asks for something an accepted decision forbids, name the decision and ask: supersede it, or make a one-time exception. Record only a supersede.
## Precedence
An accepted decision overrides this skill's rules and your own judgment. A proposed decision overrides nothing. When a decision would break a rule that blocks a merge ([definition-of-done.md](definition-of-done.md#review)), such as tokens readable by JavaScript, state the risk once before you record it, and write the risk under Consequences.

View File

@ -1,89 +0,0 @@
# Definition of Done and review
Read it when you finish a task and write the PR, or when you review code.
Contents: Checklist · B2C/B2B additions · Review
## Checklist
Copy this list and the list in B2C/B2B additions below into the PR description, and tick every item. Error handling adds its own list ([error-handling.md](error-handling.md#definition-of-done)).
```
Structure
[ ] Code is in the right project and folder, under src/, named per the naming rules
[ ] Each new or moved component went through "Choosing where a component goes"; its path, level, and reason are in the PR
[ ] Public API is exported by name from index.ts (and server.ts); no export *
[ ] ESLint boundaries pass; no upward or cross-product imports
[ ] Repositories have no client-side dependencies; UI and stores use *Payload types only
[ ] Repositories send requests only through their feature's http.ts client; no fetch outside the HTTP lib
[ ] Env is read only in the app's env/ files and through each project's getEnv(); no process.env elsewhere
[ ] No hard-coded env value, fallback, or schema default; every env value comes from the app's .env, and only apps have .env files
[ ] Every action emits its event when it succeeds, unless called with { emit: false }
[ ] No tokens or personal data in cookies or local storage; neither is read during render
[ ] Every new pattern answers a named signal and sits where design-patterns.md puts it; none is on its "Not used here" list
[ ] Each new or moved section went through rendering-patterns.md's "Choosing where a part loads"; its row in the page's rendering doc names its HTML, JS, and Index values
[ ] Every new or changed page has its rendering doc in docs/pages/<app>/ and its line in docs/pages/README.md, added or updated in this PR as page-rendering.md's "Keeping docs current" says; the doc passes its ready-for-review checks and matches the production HTML of both templates
[ ] 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 /_next/static/ JS and CSS, fonts, and symbol-defs.svg: content-hashed JS and CSS cache first, the rest stale-while-revalidate; /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, in the first flush, from its first-paint data; it says only what the page shows, the same for every visitor and in both templates; 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
States and feedback
[ ] Loading, empty, error, and in-progress states exist
[ ] Every noindex or blocked page has a skeleton (loading.tsx), and no indexable page has a loading.tsx above it; every part that loads on its own has its own Suspense skeleton and part boundary (EB-S); the app has EB-W
[ ] Every completed action shows a toast, and every failed one the action-error toast with its hint or reference ID; reads never toast
[ ] Errors follow error-handling.md: 404 and 403 reads show their empty state, ABORTED and 401 stay silent, retries follow the cause, 5xx and logic errors are reported once
[ ] Query cache is updated or invalidated after every mutation; no stale data is visible
[ ] Refetches never swap content for a spinner; keys are stable
Quality
[ ] All UI text comes from i18next; RTL and LTR both render correctly
[ ] AA contrast, focus-visible rings, keyboard operation
[ ] oxlint, prettier, ESLint boundaries, and type-check pass for affected projects
```
## B2C/B2B additions
```
[ ] 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 } } and htmlLimitedBots: /.*/
[ ] 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
[ ] useSuspenseQuery only on queries the server prefetched
[ ] global-error.tsx, error.tsx in every route group, and not-found.tsx where notFound() is called; error pages are noindex
[ ] Server reads that can answer 404 or 403 go through readOnServer; every streamed part has a PartBoundary
[ ] Each template's first flush holds the page's primary content: the H1, the main data, the breadcrumb, the LCP image, the JSON-LD, and the links that are the only path to other pages; the page entry and every Server Component outside a Suspense await only the First flush reads, the reads the primary content needs
[ ] Both templates hold the same H1, primary content, internal links, image URLs and alt texts, title, description, canonical, robots, JSON-LD, and status; collapsed content stays in the DOM
[ ] Links are <a href> with real URLs in the server HTML; menus, tabs, drawers, and sliders render the links and panels that search engines need while closed; pagination and indexable filters are links with self-canonical URLs
[ ] Indexable pages have no loading.tsx, and no Suspense around children, above them, and every link to them is the platform's NavLink; entity pages answer a missing entity with a real 404 and a replaced one with a 308
[ ] robots.ts disallows /search, /compare, and, on listing paths only, sort orders and non-indexable filters; never product pages or their variant URLs, cart, or checkout
[ ] The template is chosen by device class only, never isBot; where the repo has a unit test runner, a unit test pins Googlebot Smartphone to the mobile template; the reverse proxy or CDN adds Vary: User-Agent to HTML responses
[ ] Time-dependent UI reads useClock behind a same-size skeleton; no clock in a client component's render; absolute dates in server-rendered output are formatted on the server; nothing refreshes when a countdown ends
[ ] The server render is the same for every visitor: no session reads, no auth cookies forwarded, no viewer-dependent variant picked on the server; auth-dependent parts render their skeleton until the browser knows the viewer, unless the developer asked otherwise
[ ] Page is a thin entrypoint that renders the server-chosen mobile or desktop template
[ ] 'use client' only on interactive leaves; no server-only code reachable from client bundles
[ ] New server-only code is exported through server.ts and starts with import 'server-only'
[ ] First-load JS and each template's uncompressed HTML within budget, measured as page-rendering.md shows (next build no longer prints first-load JS); heavy widgets and third-party scripts deferred; a heavy client component that one template renders loads through next/dynamic
[ ] 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, and hreflang; every indexable page's JSON-LD follows lib-json-ld.md and passes the Rich Results Test
[ ] Fixed metadata and viewport values use the metadata and viewport exports; generateMetadata and generateViewport only for values that depend on the request or on data
[ ] Every root layout's viewport spreads ROOT_VIEWPORT (width=device-width, initial-scale=1, maximum-scale=1); never userScalable: false
[ ] The manifest's background_color and theme_color match theme.css, and it has the maskable 512 icon; every root layout's metadata includes APPLE_WEB_APP from configs/pwa.ts, and every startup image it lists exists in public/pwa/splash/
[ ] 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
```
## Review
Every review comment names the rule, shows the problem, and proposes the fix. For example:
> **Repositories stay server-safe:** `products.ts` reads the page size with `storage.getItem`, which breaks server rendering. Pass `pageSize` in `ListProductsArgs` and read the stored value in an effect of the `use-products-page` model.
Name a code smell and its technique, with the target layer or file, as [refactoring.md](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 [design-patterns.md](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; 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 change to what a page's server HTML holds, or to when its code loads, without the matching rendering doc change; primary content, JSON-LD, or the only link to a page missing from the first flush of either template; an indexable page with a `loading.tsx`, or a `<Suspense>` around `children`, above it; a page not rendered per request, or a web-vitals, bundle-budget, or HTML-size regression. Everything else is a suggestion with a rationale.

View File

@ -1,389 +0,0 @@
# Design patterns
How to pick and apply the GoF patterns from refactoring.guru and the JavaScript and React patterns from patterns.dev in this architecture. You already know the patterns, so this file gives only the decisions for this codebase: the signal that calls for each pattern, where it lives, its TypeScript shape, and when not to use it. Rendering and loading patterns are in [rendering-patterns.md](rendering-patterns.md), and code smells and refactoring techniques are in [refactoring.md](refactoring.md). Names match the source pages under refactoring.guru/design-patterns/ and patterns.dev/vanilla/ or patterns.dev/react/.
Contents: How to choose · Patterns the architecture already uses · Adding a pattern · React and JavaScript patterns · Other GoF patterns · Not used here
## How to choose
1. **Start from a problem you have now, never from a pattern.** Name the signal, then use the smallest pattern that removes it:
- The same `switch` on a type in several places → Strategy as a `Record` map.
- The same object built in several places with small differences → a factory function.
- Several booleans that describe one flow (`isUploading`, `isProcessing`, `hasFailed`) → State as a discriminated union.
- A vendor SDK's types and calls spreading through the code → Adapter in an integration.
- A back-end field name reaching a component → Adapter in the repository's `mappers.ts`.
- One feature must react to another feature's completed operation → Observer through the action's event.
- Parts of one page that must stay in step → Mediator in the page model.
- The pieces of one widget passing the same state to each other through props → Compound component.
Without a signal, write the direct code.
2. **Reuse the pattern the architecture already has for the job** (next section). A second event bus, HTTP wrapper, store library, or cache layer is a design error.
3. **Shape it with functions, closures, modules, and object literals.** Use a class only in a stateful lib whose spec already has one: `HttpClient`, `InterceptorManager`, `CookieAdapter`, or `LocalStorageAdapter`. Compose instead of inheriting. Error classes such as `HttpError` extend `Error`, and island's error-boundary primitive (`packages/island/src/primitives/error-boundary/ErrorBoundary.tsx`) extends React's `Component`, because React has no hook for catching render errors. Nothing else inherits, and no component inherits from another component.
4. **Keep a pattern inside its layer.** No pattern justifies an upward or cross-product import, or a break in the feature's layer order ([project-structure.md](project-structure.md#feature-anatomy)). When two layers must meet, wire them one level up: the AppShell subscribes, and the bootstrap configures.
5. **On the server, module scope holds only startup configuration and immutable helpers built from a fixed set, such as one `Intl` formatter per supported locale and time zone.** A singleton, a flyweight pool, or a memoized value in module scope serves every request, so it never holds back-end data, rendered output, or per-request or per-user data, even when every user would see the same value ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
6. **Wait for the third case before you extract an abstraction.** Two similar blocks can stay duplicated; the third one shows what really varies. island is the exception: a second style becomes a variant at once ([refactoring.md](refactoring.md)).
7. **Make the role visible in the name**, following the repo's conventions. Factories are camelCase `create*` functions (`createHttpClient`; `makeQueryClient` keeps the name from TanStack's docs). Key factories are camelCase objects (`productKeys`). Constant maps are UPPER_SNAKE_CASE (`AUTH_EVENTS`). A class or type that wraps a browser or vendor API ends in `Adapter` (`CookieAdapter`, `AnalyticsAdapter`), and its instance takes the domain name (`cookie`, `analytics`). A strategy map is a constant map named `<SUBJECT>_<ROLE>` (`ORDER_STATUS_BADGES`). A state machine lives in `<flow>-flow.ts` and exports `<Flow>State`, `<Flow>Event`, `<flow>Reducer`, and `INITIAL_<FLOW>_STATE`, with dotted event types that name what happened (`file.selected`).
8. **Record a new, non-obvious pattern** in the PR description: the signal, the pattern, and the simpler option you rejected.
## Patterns the architecture already uses
Reuse these before you add anything.
| Pattern | Where it lives | Rule |
|---|---|---|
| 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; 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; 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 |
| Mediator | The page model, between its part models | When parts of one page must stay in step. Parts never import or call each other: the page model owns what they share (the current step, the final submit) and passes it down as props. Don't add a context or a store for one page's parts. Run the page model in the smallest client component that contains the coordinated parts, never in the template or the page, which stay Server Components ([b2c-b2b.md](b2c-b2b.md#rendering)). State that must survive a reload or a shared link goes in the URL |
| Command | `useMutation` around a repository call or a feature action | When the UI triggers an operation and shows its progress. The mutation holds the operation; the UI calls `mutate` and reads `isPending` and `error`, and an error toast's retry calls it again when running it twice is safe ([error-handling.md](error-handling.md#actions)). Feature actions are client-side operations, not Next.js Server Actions. No hand-made command objects with `execute` and `undo`; undo is a back-end operation offered in the toast. A multi-step flow with its own states runs the request from its State reducer's model instead; don't wrap the same call in `useMutation` as well. A form whose submit runs a feature action awaits it inside `form.handleSubmit` and uses `formState.isSubmitting` as its pending state ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)); don't wrap the action in `useMutation` as well. A form that saves through one repository call keeps the model's `useMutation` ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)) and awaits `mutateAsync` inside `form.handleSubmit`, catching the error for `applyServerErrors`, so `isSubmitting` and `isPending` agree |
| State | Multi-step flows: wizards, imports, bulk actions | When a flow has steps that carry different data: a state union, an event union, and a pure reducer in the model's folder (example below). Never a set of booleans |
| Strategy | Function-valued options such as the HTTP lib's `mapErrorBody` and `shouldRefresh`; sort comparators; the mobile or desktop template that the page picks on the server | When one contract has interchangeable implementations: pass a function, or pick an entry from a `Record` map (example below). Choose once, at the top: the page picks the template, and no component branches on viewport size. Don't add a strategy for behavior that never varies |
| Composite | Navigation menus, sidebar groups, and category trees | When a tree mixes leaves and groups: one node type (`children?: MenuNode[]`) and one recursive component. Filter the tree before rendering, so a group with no visible items disappears, and key nodes by id, never by index |
| Bridge | Semantic tokens over primitive tokens in island `theme.css` | For every component and theme. Components use semantic tokens only, and each theme maps them to primitives, so components and themes vary independently and a new theme touches only `theme.css` ([code-patterns.md](code-patterns.md#tokens-and-tailwind-wiring)). Never add a theme prop, `dark:` classes, or theme-specific variants to a component |
| Flyweight | The icon sprite, where every `<use>` points at one `<symbol>`; `Intl` formatters shared per locale and time zone in `packages/tools` | When many uses share heavy, immutable data: share that part and pass the rest per use (size and color for an icon, the value for a formatter). Date formatters always set `timeZone` explicitly to the one the server chose, never the runtime default ([b2c-b2b.md](b2c-b2b.md#hydration-and-navigation)). On the server, build a pool only from a fixed set such as the app's locales and supported time zones, never from user input, and never store formatted output |
| Memento | Persisted stores (`partialize`, `version`, `migrate`); react-hook-form `defaultValues` and `reset` | When state must be restored later. Snapshot only what must survive, and migrate old snapshots ([code-patterns.md](code-patterns.md#persisted-store)). After a successful save, `reset` the form with the saved values, so dirty tracking and the unsaved-changes warning start from the saved data. Never snapshot server data or loading flags |
| Iterator | `useInfiniteQuery` for feeds; an async generator in a repository | When code walks a paged collection without caring how the pages load. Infinite queries serve feeds only. Use an async generator over pages only when a flow must visit every page and the back end has no bulk endpoint |
| Container/Presentational with Hooks | Models with presentational pages, templates, and organisms; on the server, async server components that read caches | For every page and part. The model holds the data and handlers, and the page calls it and renders a template that only takes props. On the server, the container is an async server component that reads caches and passes `*Payload` props ([b2c-b2b.md](b2c-b2b.md#data-flow)). Components never call repositories or actions directly |
| Provider | The AppShell's providers; compound component contexts | For app-wide services, such as the query client and i18next, and for the parts of one compound component. Render `<Context value>` and read it with `use(Context)` or `useContext` (React 19). Keep app-wide providers in the AppShell, and keep shared state out of context (see Provider below) |
| Compound | `DataTable` and other complex island organisms | When a widget's parts share state and the caller arranges them: the parts share state through context and are also exported by name (example below). A component with one fixed layout takes props instead |
| Render props | Slots for `DataTable` cells, empty states, and toolbars | When the caller varies part of an organism: a `ReactNode` slot by default, and a render function (`cell: (row: TRow) => ReactNode`) only when the slot needs the organism's data. Never use one to share logic; write a hook |
## Adding a pattern
Where a new implementation goes:
| Pattern | Home | Shape |
|---|---|---|
| Strategy map | The owning module's `constants.ts`. Other features import it through that feature's `index.ts`. Use `shared/constants/` only when neither its keys nor its values come from a feature, because `shared/` never imports from `features/` | A constant map named `<SUBJECT>_<ROLE>`, typed with `satisfies Record<Union, Entry>`. Styles that vary by a prop are cva variants instead |
| State machine | The page or part model's folder, such as `models/product-import/product-import-flow.ts` | The state union, the event union, and a pure reducer. The model runs it with `useReducer`. When the flow must outlive the page, move the flow file into the store's folder (`stores/<domain>/<flow>-flow.ts`), have the store's action call the reducer, and have the model read the state through a selector. A store never imports from `models/` |
| Adapter for a vendor SDK | `packages/integrations/src/<name>/` | An object literal or functions typed by the integration's own `types.ts`, with no vendor type in its public API |
| Adapter for an API shape | The repository's `mappers.ts` | `to<Name>Dto(args)` and `to<Name>Payload(dto)` ([code-patterns.md](code-patterns.md#repository)) |
| Facade over several repositories or side effects | An action in the feature that owns the operation: `actions/<action-name>/actions.ts` | One async function with the `{ emit }` option that emits its event last ([code-patterns.md](code-patterns.md#action)) |
| Observer listener | An effect of the AppShell | Subscribe once, and return the unsubscribe function as the effect's cleanup |
| Factory | Beside what it builds: in the module's main file when the module exists to build that thing (`createHttpClient` in `http.ts`), otherwise its own `create-<thing>.ts` in the owning module | `create<Thing>(options): Thing`, returning an object literal or a closure |
| Exhaustive check | `assertNever` in `packages/tools/src/assert-never/` | `assertNever(value: never): never` throws. Call it in the `default` of every `switch` over a union |
| Generic hook with no feature data, such as `useDebouncedValue` or `useClock` ([rendering-patterns.md](rendering-patterns.md#time-dependent-ui)) | `packages/tools/src/use-debounced-value/use-debounced-value.ts` when more than one project needs it; otherwise beside its only user, such as an organism's `hooks/` | A `use-<name>.ts` hook that takes plain values and imports only React. A hook that reads a store, a query, or a `*Payload` belongs in the owning feature's `models/` or beside its store |
The examples use feature paths relative to `platforms/<platform>/src/`, as code-patterns.md does.
**Strategy.** An order's status picks its badge in the order list, the order header, and the timeline. One map replaces the three switches, and `satisfies` makes a new status fail type-check until it has an entry.
`features/orders/constants.ts`
```ts
import type { BadgeProps } from '@project/island/atoms/badge';
import type { OrderStatus } from './entities/order';
export const ORDER_STATUS_BADGES = {
pending: { variant: 'warning', labelKey: 'orders:status.pending' },
paid: { variant: 'info', labelKey: 'orders:status.paid' },
shipped: { variant: 'info', labelKey: 'orders:status.shipped' },
delivered: { variant: 'success', labelKey: 'orders:status.delivered' },
cancelled: { variant: 'danger', labelKey: 'orders:status.cancelled' },
} as const satisfies Record<OrderStatus, { variant: NonNullable<BadgeProps['variant']>; labelKey: string }>;
```
A component reads `const badge = ORDER_STATUS_BADGES[order.status]` and renders `<Badge variant={badge.variant}>{t(badge.labelKey)}</Badge>`.
**State.** A product import goes `idle → validating → uploading → processing → done | failed`. The flow file holds the states, the events, and a pure reducer. An event that doesn't fit the current state returns the state unchanged.
`features/catalog/models/product-import/product-import-flow.ts`
```ts
import { assertNever } from '@project/tools/assert-never';
import type { ProductImportReportPayload } from '../../repositories/product-imports';
export type ProductImportState =
| { status: 'idle' }
| { status: 'validating'; file: File }
| { status: 'uploading'; file: File; percent: number }
| { status: 'processing'; file: File }
| { status: 'done'; report: ProductImportReportPayload }
| { status: 'failed'; error: unknown };
export type ProductImportEvent =
| { type: 'file.selected'; file: File }
| { type: 'file.validated' }
| { type: 'upload.progressed'; percent: number }
| { type: 'import.succeeded'; report: ProductImportReportPayload }
| { type: 'import.failed'; error: unknown }
| { type: 'import.cancelled' };
export const INITIAL_PRODUCT_IMPORT_STATE: ProductImportState = { status: 'idle' };
export function isProductImportBusy(state: ProductImportState): boolean {
return state.status === 'validating' || state.status === 'uploading' || state.status === 'processing';
}
export function productImportReducer(state: ProductImportState, event: ProductImportEvent): ProductImportState {
switch (event.type) {
case 'file.selected':
return isProductImportBusy(state) ? state : { status: 'validating', file: event.file };
case 'file.validated':
return state.status === 'validating' ? { status: 'uploading', file: state.file, percent: 0 } : state;
case 'upload.progressed':
if (state.status !== 'uploading') return state;
return event.percent < 100 ? { ...state, percent: event.percent } : { status: 'processing', file: state.file };
case 'import.succeeded':
return state.status === 'uploading' || state.status === 'processing'
? { status: 'done', report: event.report }
: state;
case 'import.failed':
return isProductImportBusy(state) ? { status: 'failed', error: event.error } : state;
case 'import.cancelled':
return INITIAL_PRODUCT_IMPORT_STATE;
default:
return assertNever(event);
}
}
```
`features/catalog/models/product-import/use-product-import-page.ts`. The progress comes from the feature client's `upload()` through the repository ([lib-http.md](lib-http.md#files)). The server answers with the report after it processes the file, so the flow enters `processing` when the upload reaches 100%.
```ts
import { useReducer, useRef } from 'react';
import * as v from 'valibot';
import { productImportFileSchema } from '../../../../shared/validations';
import { productImportsRepository } from '../../repositories/product-imports';
import { INITIAL_PRODUCT_IMPORT_STATE, productImportReducer } from './product-import-flow';
export function useProductImportPage() {
const [state, dispatch] = useReducer(productImportReducer, INITIAL_PRODUCT_IMPORT_STATE);
const controllerRef = useRef<AbortController | null>(null);
async function start(file: File) {
if (controllerRef.current) return;
const controller = new AbortController();
controllerRef.current = controller;
dispatch({ type: 'file.selected', file });
try {
await v.parseAsync(productImportFileSchema, file);
if (controller.signal.aborted) return;
dispatch({ type: 'file.validated' });
const report = await productImportsRepository.upload(
{ file },
{
signal: controller.signal,
onProgress: ({ percent }) => dispatch({ type: 'upload.progressed', percent }),
},
);
if (controller.signal.aborted) return;
dispatch({ type: 'import.succeeded', report });
} catch (error) {
if (!controller.signal.aborted) dispatch({ type: 'import.failed', error });
} finally {
if (controllerRef.current === controller) controllerRef.current = null;
}
}
function cancel() {
controllerRef.current?.abort();
controllerRef.current = null;
dispatch({ type: 'import.cancelled' });
}
return { state, start, cancel };
}
```
- The controller is the in-flight guard: it exists from the first step, so a second `start` (a double click) returns at once. `cancel` aborts it and clears the ref, so a cancel during validation never starts the upload, and a new file can start right away.
- An aborted run dispatches nothing, so the `ABORTED` error is never shown and a late event from the old run can't touch the new one.
- After `import.succeeded`, the model also shows a toast and invalidates the product lists ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)). Both are left out here.
- The template switches on `state.status`, with `assertNever` in the `default`.
**Observer with Adapter.** The analytics integration adapts a tag manager's `dataLayer`, which needs no npm dependency. Integrations can't import features, so the AppShell wires the auth feature's event to the integration.
`packages/integrations/src/analytics/types.ts`
```ts
export type AnalyticsEvent = { name: 'login' | 'logout' | 'purchase'; params?: Record<string, string | number> };
export type AnalyticsAdapter = { track: (event: AnalyticsEvent) => void };
declare global {
interface Window {
dataLayer?: Record<string, unknown>[];
}
}
```
`packages/integrations/src/analytics/analytics.ts`. The rest of the code calls `analytics.track`, so a change of vendor touches only this file.
```ts
import type { AnalyticsAdapter } from './types';
export const analytics: AnalyticsAdapter = {
track(event) {
if (typeof window === 'undefined') return;
(window.dataLayer ??= []).push({ event: event.name, ...event.params });
},
};
```
`platforms/<platform>/src/app/app-shell/AppShell.tsx`, reduced to the subscription.
```tsx
'use client';
import { analytics } from '@project/integrations/analytics';
import { eventEmitter } from '@project/libs/event-emitter';
import { useEffect } from 'react';
import { AUTH_EVENTS } from '../../features/auth';
import type { AppShellProps } from './types';
export function AppShell({ children }: AppShellProps) {
useEffect(() => {
const unsubscribe = eventEmitter.on(AUTH_EVENTS.login, () => analytics.track({ name: 'login' }));
return unsubscribe;
}, []);
return children;
}
```
This assumes that `on` returns an unsubscribe function. Match the repo's real event-emitter signature, for example by calling its `off` in the cleanup. Loading the tag manager's script is a loading decision, covered in rendering-patterns.md.
**Compound component.** island's `Tabs` organism: the root owns the state, the parts read it from a context, and every part is exported by name.
`packages/island/src/organisms/tabs/hooks/use-tabs-context.ts`, private to the organism:
```ts
import { createContext, useContext } from 'react';
import type { TabsContextValue } from '../types';
export const TabsContext = createContext<TabsContextValue | null>(null);
export function useTabsContext(): TabsContextValue {
const context = useContext(TabsContext);
if (!context) throw new Error('Tabs parts must be rendered inside <Tabs>.');
return context;
}
```
`packages/island/src/organisms/tabs/Tabs.tsx`. Memoize the context value, so a root re-render that keeps the same tab doesn't re-render parts that sit behind a `memo` boundary. Skip `useMemo` when the repo enables the React Compiler.
```tsx
'use client';
import { useId, useMemo, useState } from 'react';
import { TabsList } from './components/tabs-list';
import { TabsPanel } from './components/tabs-panel';
import { TabsTrigger } from './components/tabs-trigger';
import { TabsContext } from './hooks/use-tabs-context';
import type { TabsProps } from './types';
function TabsRoot({ defaultValue, children }: TabsProps) {
const [activeValue, setActiveValue] = useState(defaultValue);
const baseId = useId();
const context = useMemo(() => ({ activeValue, select: setActiveValue, baseId }), [activeValue, baseId]);
return <TabsContext value={context}>{children}</TabsContext>;
}
export const Tabs = Object.assign(TabsRoot, { List: TabsList, Trigger: TabsTrigger, Panel: TabsPanel });
```
`packages/island/src/organisms/tabs/components/tabs-trigger/TabsTrigger.tsx`. `TabsPanel` reads the same context. It renders its children the first time its tab is selected, then keeps them mounted inside `<Activity mode="hidden">` while another tab is active, so switching tabs never remounts a visited panel. A panel whose content must be in the server HTML, such as product details for search engines, takes `forceMount` and is hidden with the `hidden` attribute instead. `TabsList` only renders `role="tablist"`. Arrow-key movement between tabs is left out to keep the example short.
```tsx
'use client';
import { useTabsContext } from '../../hooks/use-tabs-context';
import type { TabsTriggerProps } from './types';
import { tabsTriggerVariants } from './variants';
export function TabsTrigger({ value, children }: TabsTriggerProps) {
const { activeValue, select, baseId } = useTabsContext();
const isSelected = activeValue === value;
return (
<button
type="button"
role="tab"
id={`${baseId}-tab-${value}`}
aria-selected={isSelected}
aria-controls={`${baseId}-panel-${value}`}
className={tabsTriggerVariants({ isSelected })}
onClick={() => select(value)}
>
{children}
</button>
);
}
```
`packages/island/src/organisms/tabs/index.ts`
```ts
export { Tabs } from './Tabs';
export { TabsList, type TabsListProps } from './components/tabs-list';
export { TabsPanel, type TabsPanelProps } from './components/tabs-panel';
export { TabsTrigger, type TabsTriggerProps } from './components/tabs-trigger';
export type { TabsProps } from './types';
```
Pitfall: a Server Component can't reach a part through the root. island modules are ES modules, so on the server each export of a `'use client'` file is only a client reference. `Tabs.List` is `undefined` there, so the render fails, and the error message depends on the bundler. So Server Components compose the named parts, and `Tabs.List` stays for client components. The panels' content can stay server-rendered, and panels that search engines must read take `forceMount`:
`apps/<app>/src/app/(shop)/product/[id]/templates/product-desktop/ProductDesktop.tsx`, excerpt:
```tsx
<Tabs defaultValue="details">
<TabsList>
<TabsTrigger value="details">{t('catalog:product.tabs.details')}</TabsTrigger>
<TabsTrigger value="shipping">{t('catalog:product.tabs.shipping')}</TabsTrigger>
</TabsList>
<TabsPanel value="details" forceMount>
<ProductSpecs product={product} />
</TabsPanel>
<TabsPanel value="shipping" forceMount>
<ShippingInfo product={product} />
</TabsPanel>
</Tabs>
```
## React and JavaScript patterns
Decisions for the patterns.dev design patterns that the table above leaves open:
- **HOC**: not used for new code. Put cross-cutting behavior in a hook or a wrapper component, such as an error boundary. React's own `memo` and `lazy` are fine, and so is Next.js's `catchError`, which builds the `PartBoundary` ([error-handling.md](error-handling.md#boundaries)). `ref` is a regular prop in React 19, so new components skip `forwardRef` too.
- **Render props versus slots**: a Server Component can't pass a plain function to a client component, so it passes only `ReactNode` slots. An organism that needs render functions, such as a `DataTable` with custom cells, is rendered from a client component that defines them.
- **Provider**: context carries services and one compound component's state, never app data. Shared client state goes to a zustand store read through selectors, server state to the query cache, and form state to react-hook-form; never mirror any of them into a context. Split large contexts. The one store-in-context case is a store that must start from server data ([b2c-b2b.md](b2c-b2b.md#state-and-auth)).
- **Hooks added in React 19**: `useActionState`, `useFormStatus`, and `useOptimistic` are built for React's actions. Forms here run on react-hook-form with the model's `submit`, and optimistic toggles go through the query cache with a rollback ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)), so don't add a second pending or optimistic state for the same data. `use()` reads a streamed promise inside `<Suspense>` ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- **Mixin**: not used. Share behavior with functions, hooks, and composition, and never copy methods onto a class or a prototype.
- **Proxy object** (JavaScript `Proxy` and `Reflect`): not used in app code, because it hides behavior from readers and from the type checker. immer uses it inside zustand's `set`, so never keep a draft after `set` returns. For guarded configuration, write explicit functions, like a project's `getEnv` that throws before `setEnv` has run.
- **Prototype** (the prototype chain): only the custom prototypes lib (`packages/libs/src/custom-prototypes/`) extends built-ins. It adds each method with `Object.defineProperty` (non-enumerable), skips a name that already exists so it never overwrites a native or third-party method, declares the methods in a `declare global` block, and is listed in `sideEffects` ([project-structure.md](project-structure.md#exports-and-tree-shaking)). Import it at the top of each bootstrap. Everywhere else, write plain functions.
- **Mediator/Middleware**: patterns.dev joins two rows of the table: Mediator (the page model) and Chain of Responsibility (interceptors and `proxy.ts`). Don't add a central hub that components send messages through.
- **Server push**, such as a live order status or the progress of an import's `processing` step: poll first, with the part model's `useQuery` and a `refetchInterval` that stops when the status is final. Push is a lib change with its own spec and approval: SSE is a streaming method in the HTTP lib, as for AI UI below, so it shares the one refresh and abort, and a WebSocket client is a new lib in `packages/libs`. Never a raw `EventSource` or `WebSocket` in a model. The part model subscribes in an effect and writes each message to the query cache with `setQueryData`, never to a store.
- **AI UI Patterns**: only when the product has a chat or assistant page. The conversation is a part model's state, with each message a union by status (`streaming`, `done`, `failed`). Streamed replies need a streaming method in the HTTP lib, which is a lib change ([lib-http.md](lib-http.md)), never `fetch` in a model. The AI SDK is outside the stack, so state the reason and get approval before adding it.
- **React Stack Patterns**: a survey of tool choices, not a design pattern. The stack is fixed in [SKILL.md](../SKILL.md#2-stack), and any other pick needs a stated reason and approval.
## Other GoF patterns
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` (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.
## Not used here
Keep these out of designs, and flag each one in review with its alternative. A merge blocks only for the reasons in [definition-of-done.md](definition-of-done.md#review), which include the server-side cache and boundary cases below.
- **`getInstance` singleton classes.** Export a module instance. On the server, create per-request objects with a function such as `getQueryClient()`.
- **Module-scope per-request or per-user state on the server**, such as a `Map` of users, a memoized promise of back-end data, or a store written during render. Use a feature cache (React `cache()`), the per-request `QueryClient`, or props ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
- **A service locator or DI container.** The bootstrap is the composition root: it passes settings to libs with `configure` and values to projects with `setEnv`, and each module imports what it uses by name.
- **Base classes** such as `BaseRepository` or `BaseService`. A repository is an object literal. Shared request behavior lives in the feature client and its interceptors ([lib-http.md](lib-http.md#root-and-feature-clients)), and shared logic lives in small functions.
- **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, 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.

View File

@ -1,328 +0,0 @@
# Error handling code
The code for [error-handling.md](error-handling.md): island's error boundary, `ErrorFallback`, the part, page, and app boundaries, `readOnServer`, and the query client's error settings. Read it only when you build or change one of these. A feature that uses them needs only error-handling.md.
Contents: island's error boundary · The fallback · Part boundary · Page and app boundaries · Query client · Server reads · Actions
Paths are relative to `platforms/<platform>/src/`, as in [code-patterns.md](code-patterns.md). Each `error-boundaries/<name>/` module is shaped like `guards/`: the component or function, its `types.ts`, and `index.ts`.
## island's error boundary
`packages/island/src/primitives/error-boundary/ErrorBoundary.tsx` is a class, because React has no hook for catching render errors. It knows nothing about HTTP or reporting; the fallback does that. Its `types.ts` declares `ErrorBoundaryProps`: `children`, `fallback: (props: { error: unknown; reset: () => void }) => ReactNode`, `onReset?`, and `resetKeys?: readonly unknown[]`.
```tsx
'use client';
import { Component } from 'react';
import type { ErrorBoundaryProps } from './types';
type ErrorBoundaryState = { hasError: boolean; error: unknown };
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
state: ErrorBoundaryState = { hasError: false, error: null };
static getDerivedStateFromError(error: unknown): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidUpdate(previous: ErrorBoundaryProps) {
const keys = this.props.resetKeys ?? [];
const changed = keys.some((key, index) => !Object.is(key, previous.resetKeys?.[index]));
if (this.state.hasError && changed) this.reset();
}
reset = () => {
this.props.onReset?.();
this.setState({ hasError: false, error: null });
};
render() {
if (!this.state.hasError) return this.props.children;
return this.props.fallback({ error: this.state.error, reset: this.reset });
}
}
```
## 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';
import { Button } from '@project/island/atoms/button';
import { ErrorState } from '@project/island/molecules/error-state';
import { classifyError, describeError, handleError } from '@project/libs/error-handler';
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, 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, retry]);
if (read === 'silent') return null;
if (read !== 'boundary') return <StatusEmptyState variant={read} size={islandSize} headingRef={headingRef} />;
const { referenceId } = describeError(error, t);
return (
<ErrorState
size={islandSize}
headingRef={headingRef}
title={t(`fallback.${cause}.title`)}
description={t(`fallback.${cause}.description`)}
referenceId={referenceId && t('fallback.reference', { referenceId })}
action={
cause === 'network' ? (
<Button onClick={onRetry}>{t('fallback.try-again')}</Button>
) : (
<Button onClick={() => window.location.reload()}>{t('fallback.reload')}</Button>
)
}
/>
);
}
```
`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`.
```tsx
'use client';
import { useQueryErrorResetBoundary } from '@tanstack/react-query';
import { catchError, type ErrorInfo } from 'next/error';
import { ErrorFallback } from '../error-fallback';
import type { PartBoundaryProps } from './types';
function PartFallback({ name }: PartBoundaryProps, { error, retry, reset }: ErrorInfo) {
const queryErrors = useQueryErrorResetBoundary();
const isServerError = 'digest' in error;
return (
<ErrorFallback
error={error}
size="part"
name={name}
onRetry={() => {
queryErrors.reset();
if (isServerError) retry();
else reset();
}}
/>
);
}
export const PartBoundary = catchError(PartFallback);
```
A part in a template:
```tsx
<PartBoundary name="seller-ratings">
<Suspense fallback={<SellerRatingsSkeleton />}>
<SellerRatings sellerId={seller.id} />
</Suspense>
</PartBoundary>
```
## Page and app boundaries
`apps/<app>/src/app/(account)/error.tsx`:
```tsx
'use client';
import { ErrorFallback } from '@project/<platform>/app/error-boundaries';
import { useQueryErrorResetBoundary } from '@tanstack/react-query';
type AccountErrorProps = { error: Error & { digest?: string }; retry: () => void };
export default function AccountError({ error, retry }: AccountErrorProps) {
const queryErrors = useQueryErrorResetBoundary();
return (
<>
<meta name="robots" content="noindex" />
<ErrorFallback
error={error}
size="page"
onRetry={() => {
queryErrors.reset();
retry();
}}
/>
</>
);
}
```
`apps/<app>/src/app/global-error.tsx`. `i18n` is the app's client i18n instance, so `useTranslation` works without providers.
```tsx
'use client';
import '../styles/app.css';
import { ErrorFallback } from '@project/<platform>/app/error-boundaries';
import { i18n } from '../i18n';
export default function GlobalError({ error }: { error: Error & { digest?: string } }) {
return (
<html lang={i18n.language} dir={i18n.dir()}>
<body>
<meta name="robots" content="noindex" />
<ErrorFallback error={error} size="app" onRetry={() => window.location.reload()} />
</body>
</html>
);
}
```
The `AppShell` renders the one `Toaster`:
```tsx
const { i18n } = useTranslation();
const dir = i18n.dir();
// in the returned JSX:
<Toaster dir={dir} position={dir === 'rtl' ? 'bottom-left' : 'bottom-right'} />
```
## Query client
`configs/react-query.ts` keeps its `getQueryClient()` and dehydrate settings ([page-example.md](page-example.md)) and adds the lines below.
```ts
import { handleError } from '@project/libs/error-handler';
import { defaultShouldDehydrateQuery, QueryCache, QueryClient } from '@tanstack/react-query';
function makeQueryClient(): QueryClient {
return new QueryClient({
queryCache: new QueryCache({
onError: (error, query) => {
if (query.state.data !== undefined) handleError(error, { where: 'refetch' });
},
}),
defaultOptions: {
queries: {
staleTime: 60_000,
retry: false,
networkMode: 'offlineFirst',
throwOnError: (_error, query) => query.state.data === undefined,
},
mutations: { networkMode: 'offlineFirst' },
dehydrate: {
shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending',
shouldRedactErrors: () => false,
},
},
});
}
```
## Server reads
`app/error-boundaries/read-on-server/read-on-server.ts`, exported only through the platform's `server.ts`. `types.ts` declares `ServerRead<T> = { status: 'ok'; data: T } | { status: 'not-found' | 'no-access' }`.
```ts
import 'server-only';
import { classifyError } from '@project/libs/error-handler';
import type { ServerRead } from './types';
export async function readOnServer<T>(read: () => Promise<T>): Promise<ServerRead<T>> {
try {
return { status: 'ok', data: await read() };
} catch (error) {
const outcome = classifyError(error).read;
if (outcome === 'not-found' || outcome === 'no-access') return { status: outcome };
throw error;
}
}
```
`apps/<app>/src/app/(shop)/seller/[slug]/page.tsx`. A seller page is the same for every visitor, so it reads on the server. A page that depends on the viewer, such as an order page, loads in the browser instead, and its reads reach the fallback as browser errors ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). A seller page is an entity page: no `loading.tsx` sits above it, so when `generateMetadata` calls `readSeller`, the status is decided before the first byte. A missing seller answers 404, and an old slug 308 ([error-handling.md](error-handling.md#b2cb2b-server)). `getSeller` is a cache, so the metadata and the page share one request, and the cache keeps a failure for the request too. `movedTo` stands for the current slug, which the back end sends when the URL used an old one.
```tsx
import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { paths } from '@project/<platform>/app/navigation';
import { getDevice, getSeller, readOnServer } from '@project/<platform>/server';
import type { Metadata } from 'next';
import { notFound, permanentRedirect } from 'next/navigation';
import { SellerDesktop } from './templates/seller-desktop';
import { SellerMobile } from './templates/seller-mobile';
type SellerPageProps = { params: Promise<{ slug: string }> };
// Throws for a missing or moved seller; returns 'ok' or 'no-access'.
async function readSeller(slug: string) {
const seller = await readOnServer(() => getSeller(slug));
if (seller.status === 'not-found') notFound();
if (seller.status === 'ok' && seller.data.movedTo) permanentRedirect(paths.seller(seller.data.movedTo));
return seller;
}
export async function generateMetadata({ params }: SellerPageProps): Promise<Metadata> {
const { slug } = await params;
const seller = await readSeller(slug);
if (seller.status !== 'ok') return { robots: { index: false } };
return { title: seller.data.name };
}
export default async function SellerPage({ params }: SellerPageProps) {
const { slug } = await params;
const [device, seller] = await Promise.all([getDevice(), readSeller(slug)]);
if (seller.status !== 'ok') return <StatusEmptyState variant={seller.status} size="page" />;
return device === 'mobile' ? <SellerMobile seller={seller.data} /> : <SellerDesktop seller={seller.data} />;
}
```
- Both functions call `readSeller`. `generateMetadata` runs before the first byte, so its call sets the real status for every request that sends a `User-Agent`. The page's call decides it for a request without one, whose metadata streams, and narrows the type.
- Narrow with `status !== 'ok'` before touching `data`. Two checks such as `=== 'not-found'` and then `=== 'no-access'` never narrow the `{ status: 'not-found' | 'no-access' }` member away, so `seller.data` fails type-check. At run time `variant` is `'no-access'`, because `readSeller` has already thrown for `'not-found'`.
A server part, `.../seller/[slug]/organisms/seller-ratings/SellerRatings.tsx`:
```tsx
import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { getSellerRatings, readOnServer } from '@project/<platform>/server';
import { RatingsSummary } from './components/ratings-summary';
import type { SellerRatingsProps } from './types';
export async function SellerRatings({ sellerId }: SellerRatingsProps) {
const ratings = await readOnServer(() => getSellerRatings(sellerId));
if (ratings.status !== 'ok') return <StatusEmptyState variant={ratings.status} size="part" />;
return <RatingsSummary ratings={ratings.data} />;
}
```
## Actions
`showActionError` and `applyServerErrors`, with a login model and a mutation that use them: [code-patterns.md](code-patterns.md#validation-model-and-server-errors).

View File

@ -1,179 +0,0 @@
# Error handling
One model for every error, so each variant looks and behaves the same in every project: error boundaries at two sizes, API errors decided by status and by whether the request read data or ran an action, and one empty state. The decisions live in the error handler lib ([lib-error-handler.md](lib-error-handler.md)); this file says where each piece goes and what the user sees. The HTTP lib's `HttpError` and its codes are in [lib-http.md](lib-http.md#errors).
Contents: The model · What each failure shows · Boundaries · Reads · Actions · Empty states · B2C/B2B server · Reporting · Copy, accessibility, and i18n · Code · Definition of Done
## The model
```
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
└─> Outdated: the page runs code from an older deploy; a page reload fixes it
2) API error ─┬─> 5xx ─┬─> Read ───> EB-X
│ └─> Action ─┐
└─> 4xx ─┬─> Action ─┴─> 1. Toast 2. Retry, by cause 3. Guide (the hint)
└─> Read ───> ES (404, 410, 403) | EB-X (the rest)
3) Empty state (ES)
```
- **EB-X** is the nearest boundary around the code that failed: the part's EB-S, else the page's EB-S, else EB-W.
- **EB-W** sits only at the app root, above the root layout, and catches only what nothing below it caught. It replaces the whole app, so it is the last resort.
- **EB-S** has two sizes. A page-size EB-S sits inside the layouts, so a failed page keeps the header, navigation, and breadcrumbs usable. A part-size EB-S (`PartBoundary`) wraps each part that loads on its own, so one failed part never takes down the page ([SKILL.md](../SKILL.md#3-architecture-rules)).
- **Read** means getting information: queries, server component reads, and the data a page loads. **Action** means a write the user started: a mutation or a feature action.
- Reads never toast. A failed read shows where its data would be, as an empty state or a fallback. Actions always toast, because the user is waiting for the result and the page they started from is still there.
- **Empty state** covers every "nothing to show" case: a successful response with no items, a filter with no matches, a 404 or 410, and a 403.
## What each failure shows
`classifyError` in the lib turns every error into these outcomes ([lib-error-handler.md](lib-error-handler.md#classification)).
| Failure | Read | Action |
|---|---|---|
| 5xx | EB-X, network fallback with Try again; reported | Toast with the support sentence and reference ID; Try again re-runs it when that is safe; reported |
| No response, timeout | EB-X, network fallback with Try again | Toast with the message and hint; Try again when safe |
| 404, 410 | ES `not-found` | Toast; Reload loads the latest data |
| 403 | ES `no-access` | Toast |
| 400, 422 | EB-X | Field errors, form alert, and toast; the user fixes and resubmits |
| 408 | EB-X, Try again | Toast; the form stays filled and submit is the retry |
| 409 | EB-X | Toast; Reload loads the latest data before the user tries again |
| 429 | EB-X | Toast whose hint says how long to wait; no button |
| 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.
- "When safe" means the action can run twice without harm: an idempotent request (PUT, DELETE, or a POST with an idempotency key the back end honors), or a read-only step. Otherwise the toast has no button, the form keeps its values, and submitting again is the retry.
## Boundaries
| Boundary | Where |
|---|---|
| EB-W | `apps/<app>/src/app/global-error.tsx` |
| EB-S, page | `app/<route-group>/error.tsx` in every route group, and `not-found.tsx` at the root and in each group that calls `notFound()` |
| EB-S, part | `PartBoundary`, built with Next.js's `catchError` |
Every boundary renders the same `ErrorFallback`, which decides what the user sees:
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 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:
- Part boundaries use `catchError`, not island's `ErrorBoundary`: `catchError` lets `notFound()` and `redirect()` through, clears itself on client navigation, and its `retry()` renders server parts again on the server. It is a higher-order function, the one exception to "no HOCs in new code" next to React's `memo` and `lazy` ([design-patterns.md](design-patterns.md#react-and-javascript-patterns)).
- `global-error.tsx` replaces the root layout, so it has no providers and no styles: it renders its own `<html>` and `<body>`, imports `app.css` and the client i18n setup itself, and offers Reload page.
- 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)), 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
- `configs/react-query.ts` sets `throwOnError: (_error, query) => query.state.data === undefined`. A first load that fails throws to its boundary; a refetch that fails keeps the data and shows nothing. Parts guard only `isPending`, never `isError`, so no component has an error branch.
- `useSuspenseQuery` always throws on a failed first load, whatever `throwOnError` says, so it reaches the same boundary.
- `QueryCache.onError` calls `handleError(error, { where: 'refetch' })` only when the query still has data: that is the one place a failed refetch stops. A first load is handled by its fallback instead.
- Queries don't retry on their own (`retry: false`), because the HTTP lib already retried idempotent requests. The user retries from the fallback.
- `networkMode: 'offlineFirst'` for queries and mutations, so an offline request fails at once and shows the network fallback or toast, instead of pausing with a skeleton or spinner that never ends.
- A read whose 404 or 403 is an expected answer (a detail page, an order that may belong to someone else) needs no special code: the fallback turns it into the `not-found` or `no-access` empty state.
## Actions
- A form catches the action's error in `form.handleSubmit` and calls `applyServerErrors`. Anything else calls `showActionError` in its `catch` or in `useMutation`'s `onError`. Code: [code-patterns.md](code-patterns.md#validation-model-and-server-errors).
- `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`, 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.
- An action that runs inside `startTransition` catches its error inside the transition. An error thrown out of a transition goes to the nearest error boundary and replaces the part, which is wrong for an action.
- Uploads and multi-step flows keep a `failed` state in their reducer and also call `showActionError`, with a `retry` that starts the flow again with the same file ([design-patterns.md](design-patterns.md#adding-a-pattern)).
- Login and OTP requests send `skipRefresh: true`, and the back-end contract answers wrong credentials with 400 or 422 and field errors. So a 401 always means "no valid session", and the login form never triggers a refresh.
## Empty states
- island has one `EmptyState` molecule (`packages/island/src/molecules/empty-state/`) with the variants `no-data`, `no-results`, `not-found`, and `no-access`, and the sizes `part` and `page`. Each variant has its own illustration. It takes the title, description, and an optional action as props, so each use gives its own copy.
- Its sibling `ErrorState` molecule has the same sizes and slots, plus a `referenceId` line, for the fallbacks.
- `no-data` and `no-results` come from successful responses: the template renders them from the model's data, with feature copy and a primary action ("No categories yet. Create your first category to start organizing products." and "Create category"). `no-results` offers "Clear filters".
- `not-found` and `no-access` come from errors. The app's `StatusEmptyState` renders them with shared copy from the `errors` namespace; the page size adds a link to the home page.
- A list part that hides itself when empty, such as a related-products rail, may render nothing instead. Decide it in the plan, not per render.
## B2C/B2B server
Server reads classify on the server, because a Server Component error reaches the browser with only its digest.
- 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)).
- Where `notFound()` runs decides the status:
- An indexable page has nothing above it that streams: no `loading.tsx`, and no `<Suspense>` around `children` in a layout or in a component that a layout renders around them ([b2c-b2b.md](b2c-b2b.md#rendering)). On an entity page (product, category, brand, seller, article, store branch, campaign), `generateMetadata` and the page call one read helper. The helper reads through `readOnServer` and the page's cache, calls `notFound()` for `not-found`, and calls `permanentRedirect()` when the payload names a replacement ([error-handling-code.md](error-handling-code.md#server-reads)). `generateMetadata` runs before the first byte, so crawlers get a real 404 with `noindex` in `<head>`, at no extra read, or a 308 with `Location`. The page's call covers a request without a `User-Agent`, whose metadata streams.
- The server HTML of a real 404 has an empty `<body>`, and the group's `not-found.tsx` renders in the browser. Google needs only the status, and it may not render a non-200 page at all.
- Moves known in advance, such as a renamed category tree, go in `redirects()` in `next.config.ts`, which answers before any render. A redirect thrown while the shell renders, or a failed read that `generateMetadata` rethrows, makes Next.js render again with a fresh cache, so the read runs twice. A back-end outage therefore doubles the reads that `generateMetadata` awaits, as on entity pages.
- A `noindex` or blocked page keeps its `loading.tsx`, so its status is already 200 when `notFound()` runs. Next.js then adds a `noindex` robots tag, in `<head>` when `generateMetadata` throws and at the end of `<body>` when the page throws, and renders the not-found UI only in the browser. A redirect becomes a `<meta http-equiv="refresh">`.
- `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.
- `instrumentation.ts` configures the error handler for the server and calls `handleError` from `onRequestError` ([lib-error-handler.md](lib-error-handler.md#usage)).
Status per case, measured on Next.js 16.4. No page answers 410: Google treats it like 404, and Next.js has no API for it.
| Case | Status | The server HTML holds |
|---|---|---|
| Entity missing | 404 | `noindex` in `<head>` and an empty `<body>`; `not-found.tsx` renders in the browser |
| Entity replaced by another | 308 to the replacement | nothing that matters |
| Product out of stock, or discontinued with its content kept | 200, indexable | the page, with its stock text, and its availability in the JSON-LD |
| Listing page past the last; empty, duplicate, or unknown combination of indexable filters | 404 | as for a missing entity |
| Empty listing whose URL includes a filter that `robots.ts` blocks | 200 | the listing, with the `no-results` empty state and Clear filters |
| Category with no products | 200 with `noindex` while the menu links it; 404 once it leaves the menu | the page, with the `no-data` empty state |
| Search with no results | 200; `/search` is blocked in `robots.ts` | the `no-results` empty state; never 5xx for an unknown query |
| A failed read on an indexable page, in `generateMetadata`, the page entry, or another Server Component outside every `<Suspense>` | 500 | `noindex` and an empty `<body>`; `error.tsx` renders in the browser |
| A failed read in a part inside its `<Suspense>` and `PartBoundary` | 200 | the part's skeleton; the `PartBoundary` fallback renders in the browser |
| A failed read in a layout above the page, such as the `(shop)` layout's `getMenu()` | 500, on every page under that layout | `noindex` and an empty `<body>` |
| `notFound()` on a `noindex` or blocked page, under its `loading.tsx` | 200 | the skeleton and `noindex`; the not-found UI renders in the browser |
| A failed read on a `noindex` or blocked page, under its `loading.tsx` | 200 | the skeleton; a `noindex` page keeps the `noindex` of its `metadata` export, and a blocked page has no robots tag; `error.tsx` and its `noindex` render in the browser |
| Overload | 503 with `Retry-After`, from the reverse proxy or the CDN | — |
## Reporting
- `handleError` runs once per error, where it stops: a fallback, `showActionError`, `QueryCache.onError`, or the server's `onRequestError`. Never call it in a repository, an action, or a `catch` that rethrows.
- It reports 5xx and logic errors only, with the request id and digest. 4xx, network, and timeout errors aren't bugs; the HTTP lib's breadcrumbs keep them visible next to a reported error.
- The bootstrap passes the Sentry integration's adapter as `report`. The adapter maps an `ErrorReport` to the vendor's event (tags: `where`, `status`, `code`; context: `requestId`, `digest`, `name`) and filters noise that isn't the app's bug, such as errors thrown by browser extensions.
- No failure events on the event emitter: events announce completed operations only ([design-patterns.md](design-patterns.md#not-used-here)).
## Copy, accessibility, and i18n
- Every fallback, empty state, and toast says what happened and what the user can do, following the copy rules in [ui-rules.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 (`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).
## Code
The boundaries, `ErrorFallback`, `readOnServer`, and the query client's error settings are in [error-handling-code.md](error-handling-code.md). Read it only when you build or change one of them.
## Definition of Done
```
[ ] The app has EB-W; every page and every part that loads on its own has an EB-S, and every boundary renders ErrorFallback
[ ] Reads never toast: 404 and 410 show the not-found empty state, 403 no-access, and other failures their boundary's fallback
[ ] A failed refetch keeps its data; no component has an isError branch
[ ] 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
[ ] Server reads go through readOnServer; error pages and no-access pages are noindex
[ ] Indexable pages have no loading.tsx, and no Suspense around children, above them; an entity page's generateMetadata answers a missing entity with notFound() (404) and a replaced one with permanentRedirect() (308) before the first byte
```

View File

@ -1,109 +0,0 @@
# Cookie lib (`packages/libs/src/cookie`)
One small `CookieAdapter` class over `document.cookie`: get, set, and remove with encoding, safe defaults (`path=/`, `SameSite=Lax`, `Secure`), and per-call options. Browser only; framework-agnostic; no dependency (no js-cookie).
Contents: What cookies are for · Structure · Types · API · Keys · Browser only · Server side · Usage · Acceptance checklist
## What cookies are for
- Only small values the server must see on the request: `theme` (so the server renders it without a flash), a `locale` preference, and the consent choice. A locale cookie never decides the locale of an indexable page, which its URL decides ([ui-rules.md](ui-rules.md#crawlers)), and no cookie picks the mobile or desktop template, which comes from the User-Agent's device class only ([b2c-b2b.md](b2c-b2b.md#rendering)).
- Every cookie is sent with every request to its domain and path and holds about 4 KB. Anything the server doesn't need goes to local storage ([lib-local-storage.md](lib-local-storage.md)).
- Never auth tokens. Auth cookies are `HttpOnly`, set and rotated by the server, and JavaScript can't and mustn't read them (see [lib-http.md](lib-http.md), Refresh token). Never secrets or personal data.
## Structure
```
packages/libs/src/cookie/
├── cookie.ts # CookieAdapter class and the shared `cookie` instance
├── types.ts # CookieAdapterAbstraction, CookieOptions
├── constants.ts # DEFAULT_COOKIE_OPTIONS
└── index.ts
```
- `index.ts` exports `CookieAdapter`, `cookie`, `DEFAULT_COOKIE_OPTIONS`, and the types `CookieAdapterAbstraction` and `CookieOptions`. Nothing goes in `server.ts`: the lib is browser-only.
- Import by subpath: `import { cookie } from '@project/libs/cookie'`.
## Types
```ts
interface CookieOptions {
path?: string; // default '/'
domain?: string; // default: none (current host only); set it to share with subdomains, e.g. '.example.com'
maxAgeDays?: number; // lifetime in days; omit for a session cookie
sameSite?: 'Strict' | 'Lax' | 'None'; // default 'Lax'
secure?: boolean; // default true; forced to true when sameSite is 'None'
}
interface CookieAdapterAbstraction {
get(key: string): string | null;
set(key: string, value: string, options?: CookieOptions): void;
remove(key: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void;
}
```
## API
- `get(key)` returns the decoded value, or `null` when the cookie doesn't exist. It finds the `encodeURIComponent(key)=` entry in `document.cookie` split by `'; '` and decodes the rest, so values containing `=` stay whole. A value with broken percent-encoding (written by other code) is returned raw instead of throwing.
- `set(key, value, options?)` writes `key=value` with `encodeURIComponent` on both, plus the attributes:
- Options merge in this order: `DEFAULT_COOKIE_OPTIONS` → `configure` defaults → call options.
- `maxAgeDays` becomes `max-age` in seconds (`Math.floor(days * 24 * 60 * 60)`); without it the cookie is a session cookie.
- `sameSite: 'None'` always adds `Secure`, because browsers reject it otherwise.
- `remove(key, options?)` writes the cookie empty with `max-age=0`. It must use the same `path` and `domain` the cookie was set with, or the browser keeps the original. Defaults come from `configure`, so keep them the same for set and remove.
- `configure(defaults: CookieOptions)` sets the defaults once, in the app's bootstrap. It only stores options and never touches `document`, so it's safe in `bootstrap.client.ts` during SSR. For example, `cookie.configure({ secure: clientEnv.NEXT_PUBLIC_COOKIE_SECURE })`, from the app's env, lets local development over plain `http` on a non-localhost host turn `Secure` off.
- There is no public mutable `options` property: on a shared instance, any code could change every other caller's cookies at any time. Per-call differences go in the call's options.
- The shared instance is `export const cookie = new CookieAdapter();`. Create another `CookieAdapter` only in tests.
## Keys
- Cookie names are constants in the owning project's `constants.ts` (`LOCALE_COOKIE`, `THEME_COOKIE`), never string literals at call sites.
- Names are a contract with the server: `proxy.ts`, Server Components, and the back end read the same names, so renaming one is a breaking change.
- Names are not prefixed automatically (unlike local-storage keys), because the server reads them by their exact name.
## Browser only
- Every method except `configure` checks `typeof document === 'undefined'` and throws a clear error ("cookie is browser-only; on the server read cookies with next/headers") instead of the unclear "document is not defined".
- Call it only in event handlers, effects, actions, and client bootstrap code. Never during render and never at module top level: client components also render on the server, and a value read during render differs between server and browser, which breaks hydration.
## Server side
- Server code reads cookies with `cookies()` from `next/headers` (Server Components, Route Handlers, Server Functions) or `request.cookies` in `proxy.ts`, inside the app or platform. The lib never imports Next.js.
- Server Components can't set cookies. Set them in `proxy.ts`, a Route Handler, or a Server Function on the server, or with `cookie.set` in the browser.
- A value the page needs while rendering (theme) is read on the server and passed down as a prop. The browser writes it with `cookie.set` when the user changes it, then refreshes or updates the UI.
## Usage
Bootstrap (`bootstrap.client.ts`):
```ts
cookie.configure({ secure: clientEnv.NEXT_PUBLIC_COOKIE_SECURE });
```
`features/preferences/actions/change-theme/actions.ts`
```ts
import { cookie } from '@project/libs/cookie';
import { usePreferencesStore } from '../../../../stores/preferences';
import { THEME_COOKIE, THEME_COOKIE_MAX_AGE_DAYS } from '../../constants';
import type { Theme } from '../../entities/theme';
export function changeTheme(theme: Theme): 'ok' {
cookie.set(THEME_COOKIE, theme, { maxAgeDays: THEME_COOKIE_MAX_AGE_DAYS });
usePreferencesStore.getState().setTheme(theme);
return 'ok';
}
```
## Acceptance checklist
For building or changing the lib:
```
[ ] set, get, and remove round-trip a value, including values with "=", ";", spaces, and non-Latin text (e.g. Persian)
[ ] get returns null for a missing cookie and doesn't match a cookie whose name only starts with the key ("theme" vs "theme-v2")
[ ] A value with broken percent-encoding is returned raw, not thrown
[ ] maxAgeDays writes the right max-age; no maxAgeDays writes a session cookie
[ ] sameSite 'None' always writes Secure
[ ] Call options win over configure defaults, which win over DEFAULT_COOKIE_OPTIONS
[ ] remove with the configured path and domain deletes the cookie
[ ] get, set, and remove throw the clear browser-only error on the server; configure doesn't
```

View File

@ -1,285 +0,0 @@
# Env lib (`packages/libs/src/env`)
Validates the app's environment variables and gives apps typed, read-only values. `createClientEnv` validates the public variables and is safe on both sides; `createServerEnv` validates the server variables and runs only on the server. Built on @t3-oss/env-core with valibot schemas. Framework-agnostic: the app passes its prefix and its runtime values, so the lib never reads `process.env` itself.
Only apps call it. Every other project gets its values from the app's bootstrap through its own `env/` (`setEnv` and `getEnv`), so no project below the app reads the environment.
No project hard-codes an env value. An env value is a value that changes between environments: a service or CDN address, a key, a third-party ID, a feature flag. Every env value comes from the `.env` of the app that serves it, and only apps have `.env` files.
Contents: Structure · Types · API · Validation · The app's env · Project env · Bootstrap · Implementation · Usage · Acceptance checklist
## Structure
```
packages/libs/src/env/
├── env.client.ts # createClientEnv, and the error formatter both functions use
├── env.server.ts # createServerEnv; starts with import 'server-only'
├── types.ts # EnvSchema, EnvValues, ClientEnvOptions, ServerEnvOptions
├── index.ts # createClientEnv and the types
└── server.ts # import 'server-only'; createServerEnv
```
- The project's `src/server.ts` re-exports `createServerEnv` by name.
- Import by subpath: `import { createClientEnv } from '@project/libs/env'` and `import { createServerEnv } from '@project/libs/env/server'`.
## Types
```ts
import type { StandardSchemaDictionary } from '@t3-oss/env-core';
export type EnvSchema = StandardSchemaDictionary; // variable name → valibot schema
export type EnvValues<TSchema extends EnvSchema> = Readonly<StandardSchemaDictionary.InferOutput<TSchema>>;
export type ClientEnvOptions<TPrefix extends string, TSchema extends EnvSchema> = {
prefix: TPrefix; // 'NEXT_PUBLIC_'
schema: TSchema & {
[TKey in keyof TSchema]: TKey extends `${TPrefix}${string}` ? TSchema[TKey] : `${TKey & string} must start with ${TPrefix}`;
};
runtimeEnv: NoInfer<Record<keyof TSchema, string | undefined>>; // every declared variable, each read literally
};
export type ServerEnvOptions<TSchema extends EnvSchema> = {
schema: TSchema;
runtimeEnv: Record<string, string | undefined>; // process.env
skipValidation?: boolean; // only for steps that run without the real env (see Validation)
};
```
## API
- `createClientEnv(options)` returns `EnvValues<TSchema>`.
- Every variable name must start with `prefix`. A name that doesn't is a type error: `API_SECRET must start with NEXT_PUBLIC_`.
- `runtimeEnv` lists every declared variable with a literal reference, `NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL`, because bundlers inline only literal references and the browser has no real `process.env`. Leaving one out is a type error.
- It has no `skipValidation`: public variables are inlined when the app is built, so they must be present at build time anyway.
- `createServerEnv(options)` returns `EnvValues<TSchema>`. It is server-only, so a client import fails the build, and it reads `runtimeEnv: process.env` at runtime.
- Both:
- Empty strings count as missing (`emptyStringAsUndefined`), so `API_URL=` in a `.env` file fails instead of passing as `''`.
- The values are the schema outputs, so transforms apply: `v.pipe(v.string(), v.transform(Number), v.integer())` turns `'24'` into the number `24`.
- On failure they throw one `Error` that lists every invalid variable and why:
```
Invalid environment variables:
- NEXT_PUBLIC_API_URL: Invalid URL: Received "not-a-url"
- NEXT_PUBLIC_CDN_URL: Invalid type: Expected string but received undefined
```
- The result is read-only, and reading an undeclared variable is a type error.
## Validation
- Validation runs when the app's env module first loads. Both bootstraps import it first, so a bad variable stops the app with one clear error before any page renders.
- Next.js: to fail the build instead, load `env/env.client.ts` from `next.config.ts` (with jiti when the config can't resolve it). Never load `env.server.ts` there: `server-only` throws outside the React server graph.
- `skipValidation` (server env only) is for steps that run without the real env: lint, type-check, and a Docker image build without runtime secrets. The app sets it from a flag (`SKIP_ENV_VALIDATION=true`). Skipped validation returns the raw strings without transforms, so a running app never sets it.
- Messages come from the schemas, and valibot's default messages repeat the received value. Give every secret's schema its own message (`v.minLength(32, 'Use at least 32 characters')`), and never log env values.
## The app's env
```
apps/<app>/src/env/
├── env.client.ts # public variables: export const clientEnv = createClientEnv({ ... })
├── env.server.ts # server variables: export const serverEnv = createServerEnv({ ... }); import 'server-only'
├── index.ts # clientEnv
└── server.ts # import 'server-only'; serverEnv
```
- These files are the only code in the repo that reads `process.env`.
- App code (bootstrap, configs) reads `clientEnv` and `serverEnv` directly. Only server code imports `../env/server`.
- Every value comes from the app's `.env` files. Only apps that serve in production have `.env` files; platforms, island, libs, integrations, and tools have none.
- Every variable is required. Never give a schema a default (`v.optional(schema, 'http://localhost:3000')`) or add a fallback in code (`clientEnv.NEXT_PUBLIC_API_URL ?? '...'`). A default or a fallback is a hard-coded value that hides a missing variable.
## Project env
Every project except apps that reads env has:
```
<project>/src/env/
├── env.ts # setEnv and getEnv, for this project's values only
├── types.ts # the project's env type, e.g. IslandEnv
└── index.ts
```
- `setEnv(env)` stores the project's values. `getEnv()` returns them, and throws a clear error when called before `setEnv`.
- The type uses the project's own names (`cdnUrl`, `catalogApiUrl`), not variable names. The bootstrap maps one to the other, so renaming a variable only touches the app.
- Read `getEnv()` inside functions, never at module top level, because bootstrap may not have run yet: `baseUrl: () => getEnv().catalogApiUrl`.
- The project never imports the app or reads the raw environment, so the dependency graph stays acyclic.
- The project never hard-codes an env value: no literal address, key, ID, or flag, and no fallback for a `getEnv()` value. A new env value goes in the project's env type, and the app fills it from its `.env`.
- Libs have no project env; they never read env. The bootstrap passes their settings through `configure`: `http.configure({ baseUrl })`, `configureServerHttp({ baseUrl, getCookieHeader })`, `cookie.configure({ secure })`. A lib never has a default address, key, or ID; it gets them through `configure`.
## Bootstrap
- The app's bootstrap calls each project's `setEnv` at startup with the values that project needs. Bootstraps are idempotent, so `setEnv` may run again with the same values.
- Every project exports the same names, so import each under its project's name: `import { setEnv as setIslandEnv } from '@project/island/env'`.
- The server module graph and the client module graph each hold their own copy of every project env.
- `bootstrap.server.ts` fills the server copy. It may pass server-side values, such as an internal service address.
- `bootstrap.client.ts` fills the client copy, with public values only.
- Both must provide every field of a project's env type, so a project env never holds a secret. A secret stays in the app's `serverEnv`, and only the app's server code uses it (for example a header in `configureServerHttp`).
## Implementation
`env.client.ts`
```ts
import { createEnv, type StandardSchemaV1 } from '@t3-oss/env-core';
import type { ClientEnvOptions, EnvSchema, EnvValues } from './types';
export function throwInvalidEnv(issues: readonly StandardSchemaV1.Issue[]): never {
const lines = issues.map((issue) => {
const name = issue.path?.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.');
return `- ${name ?? 'env'}: ${issue.message}`;
});
throw new Error(`Invalid environment variables:\n${lines.join('\n')}`);
}
export function createClientEnv<const TPrefix extends string, TSchema extends EnvSchema>(
options: ClientEnvOptions<TPrefix, TSchema>,
): EnvValues<TSchema> {
return createEnv<string, {}, EnvSchema>({
clientPrefix: options.prefix,
client: options.schema,
// env-core deletes empty strings from the object it gets, so it gets a copy
runtimeEnvStrict: { ...options.runtimeEnv },
emptyStringAsUndefined: true,
onValidationError: throwInvalidEnv,
}) as EnvValues<TSchema>;
}
```
`env.server.ts`
```ts
import 'server-only';
import { createEnv } from '@t3-oss/env-core';
import { throwInvalidEnv } from './env.client';
import type { EnvSchema, EnvValues, ServerEnvOptions } from './types';
export function createServerEnv<TSchema extends EnvSchema>(options: ServerEnvOptions<TSchema>): EnvValues<TSchema> {
return createEnv<undefined, EnvSchema>({
server: options.schema,
// env-core deletes empty strings from the object it gets, so process.env gets a copy
runtimeEnv: { ...options.runtimeEnv },
isServer: true,
emptyStringAsUndefined: true,
skipValidation: options.skipValidation ?? false,
onValidationError: throwInvalidEnv,
}) as EnvValues<TSchema>;
}
```
The explicit type arguments on `createEnv` are needed, because env-core's option types can't be checked against a generic schema. Call sites stay fully typed through `ClientEnvOptions` and `ServerEnvOptions`.
## Usage
`apps/<app>/src/env/env.client.ts`
```ts
import { createClientEnv } from '@project/libs/env';
import * as v from 'valibot';
export const clientEnv = createClientEnv({
prefix: 'NEXT_PUBLIC_',
schema: {
NEXT_PUBLIC_API_URL: v.pipe(v.string(), v.url()),
NEXT_PUBLIC_CDN_URL: v.pipe(v.string(), v.url()),
NEXT_PUBLIC_CATALOG_API_URL: v.pipe(v.string(), v.url()),
},
runtimeEnv: {
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
NEXT_PUBLIC_CDN_URL: process.env.NEXT_PUBLIC_CDN_URL,
NEXT_PUBLIC_CATALOG_API_URL: process.env.NEXT_PUBLIC_CATALOG_API_URL,
},
});
```
`apps/<app>/src/env/env.server.ts`
```ts
import 'server-only';
import { createServerEnv } from '@project/libs/env/server';
import * as v from 'valibot';
export const serverEnv = createServerEnv({
schema: {
API_INTERNAL_URL: v.pipe(v.string(), v.url()),
CATALOG_API_INTERNAL_URL: v.pipe(v.string(), v.url()),
},
runtimeEnv: process.env,
skipValidation: process.env.SKIP_ENV_VALIDATION === 'true',
});
```
`packages/island/src/env/env.ts`. `types.ts` declares `IslandEnv`, and `index.ts` exports both functions and the type.
```ts
import type { IslandEnv } from './types';
let islandEnv: IslandEnv | undefined;
export function setEnv(env: IslandEnv): void {
islandEnv = env;
}
export function getEnv(): Readonly<IslandEnv> {
if (!islandEnv) {
throw new Error('island env is not set. The app bootstrap must call setEnv from @project/island/env first.');
}
return islandEnv;
}
```
`apps/<app>/src/bootstrap/bootstrap.server.ts`
```ts
import 'server-only';
import { setEnv as setIslandEnv } from '@project/island/env';
import { configureServerHttp } from '@project/libs/server';
import { setEnv as setPlatformEnv } from '@project/<platform>/env';
import { cookies } from 'next/headers';
import { clientEnv } from '../env';
import { serverEnv } from '../env/server';
setIslandEnv({ cdnUrl: clientEnv.NEXT_PUBLIC_CDN_URL });
setPlatformEnv({ catalogApiUrl: serverEnv.CATALOG_API_INTERNAL_URL });
configureServerHttp({
baseUrl: serverEnv.API_INTERNAL_URL,
getCookieHeader: async () => (await cookies()).toString(),
});
```
`apps/<app>/src/bootstrap/bootstrap.client.ts`. It also turns on refresh and registers the shared interceptors (see [lib-http.md](lib-http.md#usage)).
```ts
import { setEnv as setIslandEnv } from '@project/island/env';
import { http } from '@project/libs/http';
import { setEnv as setPlatformEnv } from '@project/<platform>/env';
import { clientEnv } from '../env';
setIslandEnv({ cdnUrl: clientEnv.NEXT_PUBLIC_CDN_URL });
setPlatformEnv({ catalogApiUrl: clientEnv.NEXT_PUBLIC_CATALOG_API_URL });
http.configure({ baseUrl: clientEnv.NEXT_PUBLIC_API_URL });
```
`platforms/<platform>/src/features/catalog/http.ts` reads the platform's env. The server copy holds the internal address and the client copy the public one.
```ts
import { http } from '@project/libs/http';
import { getEnv } from '../../env';
export const catalogHttp = http.extend({ baseUrl: () => getEnv().catalogApiUrl });
```
## Acceptance checklist
For building or changing the lib:
```
[ ] createClientEnv and createServerEnv return typed, read-only values; transforms apply
[ ] A public variable without the prefix, or a declared variable missing from runtimeEnv, is a type error
[ ] A missing, empty, or invalid variable throws one Error that lists every invalid variable and why
[ ] Importing @project/libs/env/server outside the React server graph throws (server-only), so a client import fails the build
[ ] process.env is unchanged after createServerEnv runs
[ ] skipValidation returns the raw values without validating
[ ] A project's getEnv throws the clear error before setEnv and returns the values after it
[ ] No process.env outside the app's env/ files
[ ] No hard-coded env value, fallback, or schema default; every env value comes from the app's .env, and only apps have .env files
```

View File

@ -1,259 +0,0 @@
# Error handler lib (`packages/libs/src/error-handler`)
Four functions that every project uses to decide what an error shows, what it says, and whether it is reported: `configureErrorHandler`, `classifyError`, `describeError`, and `handleError`. The model they implement (error boundaries, API errors by status, empty states) is in [error-handling.md](error-handling.md).
It is framework-agnostic (no React, Next.js, TanStack, i18next, or sonner imports), runs in the browser and on the server, and has no dependency. It imports only `isHttpError` from the HTTP lib ([lib-http.md](lib-http.md#errors)). It never shows anything: boundaries, empty states, and toasts live in the apps and platforms.
Contents: Structure · Types · API · Classification · Messages and reference ID · Reporting · Implementation · Usage · Acceptance checklist
## Structure
```
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, OUTDATED_MESSAGE_KEY, CHUNK_ERROR_PATTERN
└── index.ts
```
- `index.ts` exports the four functions and the types. Nothing goes in `server.ts`: the lib has no server-only capability, so both sides import it from `index.ts`.
- Import by subpath: `import { classifyError } from '@project/libs/error-handler'`.
## Types
```ts
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' | 'reload-page' | 'fix' | 'none';
interface ErrorClass {
cause: ErrorCause;
read: ReadOutcome;
action: ActionOutcome;
retry: RetryKind;
report: boolean; // true for 5xx and logic errors
}
type ErrorWhere = 'app' | 'page' | 'part' | 'action' | 'refetch' | 'server';
interface ErrorContext {
where: ErrorWhere; // where the error stopped
name?: string; // the part, action, or route, e.g. 'seller-ratings'; never personal data
}
interface ErrorReport extends Partial<ErrorContext> {
error: unknown;
status?: number;
code?: string;
requestId?: string;
digest?: string; // Next.js's id for a server error
}
interface ErrorHandlerConfig {
report?: (report: ErrorReport) => void; // the error-tracking integration's adapter
onForbidden?: () => void; // runs on every 403 that handleError handles
}
type TranslateFn = (key: string, options?: Record<string, unknown>) => string; // i18next's t fits
interface ErrorDescription {
message?: string; // what went wrong, only when the user can understand it
hint?: string; // how to fix it: the guide
referenceId?: string; // requestId, or the server digest
}
```
## 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 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.
## Classification
The first matching row wins.
| Error | `cause` | `read` | `action` | `retry` | `report` |
|---|---|---|---|---|---|
| `ABORTED` | network | silent | silent | none | no |
| 401 | network | silent | silent | none | no |
| 403 | network | no-access | toast | none | no |
| 404, 410 | network | not-found | toast | reload | no |
| 409 | network | boundary | toast | reload | no |
| 429 | network | boundary | toast | wait | no |
| 5xx | network | boundary | toast | again | yes |
| 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.
- 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. 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.
## Reporting
- Reports go only to the `report` callback that the bootstrap passes in, never to an event on the event emitter.
- `report` is true for 5xx and logic errors. 4xx, network, and timeout failures are the user's or the connection's, so they aren't reported; the HTTP lib's breadcrumbs keep them visible in the tracker when a reported error follows.
- An `ErrorReport` carries the error, the context, and the status, code, request id, and digest, so the tracker can group by status and code and search by reference ID. It never carries form values, cookies, or headers.
## Implementation
`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 {
CHUNK_ERROR_PATTERN,
LIB_MESSAGE_PREFIX,
NOT_FOUND_STATUSES,
OUTDATED_MESSAGE_KEY,
RETRY_AFTER_HINT_KEY,
} from './constants';
import type {
ErrorClass,
ErrorContext,
ErrorDescription,
ErrorHandlerConfig,
ReadOutcome,
RetryKind,
TranslateFn,
} from './types';
let config: ErrorHandlerConfig = {};
export function configureErrorHandler(next: ErrorHandlerConfig): void {
config = { ...config, ...next };
}
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 };
}
function getDigest(error: unknown): string | undefined {
if (typeof error !== 'object' || error === null || !('digest' in error)) return 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)) {
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');
if (NOT_FOUND_STATUSES.includes(status)) return apiError('not-found', 'reload');
if (status === 409) return apiError('boundary', 'reload');
if (status === 429) return apiError('boundary', 'wait');
if (status >= 500) return apiError('boundary', 'again', true);
if (status >= 400) return apiError('boundary', 'fix');
if (code === 'NETWORK_ERROR' || code === 'TIMEOUT') return apiError('boundary', 'again');
return LOGIC;
}
export function describeError(error: unknown, t: TranslateFn): ErrorDescription {
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';
return {
message: isUserFacing ? translate(error.message) : undefined,
hint:
translate(error.hint) ??
(error.retryAfter ? t(RETRY_AFTER_HINT_KEY, { seconds: error.retryAfter }) : undefined),
referenceId: error.requestId ?? getDigest(error),
};
}
export function handleError(error: unknown, context?: ErrorContext): ErrorClass {
const errorClass = classifyError(error);
try {
if (errorClass.report) {
config.report?.({
...context,
error,
status: isHttpError(error) ? error.status : undefined,
code: isHttpError(error) ? error.code : undefined,
requestId: isHttpError(error) ? error.requestId : undefined,
digest: getDigest(error),
});
}
if (isHttpError(error) && error.status === 403) config.onForbidden?.();
} catch {
// Handling an error must never throw a second one.
}
return errorClass;
}
```
- `config` is startup configuration, set by the bootstrap, so module scope is allowed to hold it on the server ([design-patterns.md](design-patterns.md#how-to-choose)). It never holds errors or anything per request.
- On the server, `onRequestError` sees the real `HttpError`, with the digest Next.js gave it, so the report has both ids and matches what the browser shows.
## Usage
Browser bootstrap (`bootstrap.client.ts`). The Sentry integration adapts `ErrorReport` to its vendor's event.
```ts
import { captureError } from '@project/integrations/sentry';
import { configureErrorHandler } from '@project/libs/error-handler';
configureErrorHandler({ report: captureError });
```
Server, `apps/<app>/src/instrumentation.ts`. `register()` runs once when the server starts, and `onRequestError` runs for every error that no server code caught.
```ts
import { captureServerError } from '@project/integrations/server';
import { configureErrorHandler, handleError } from '@project/libs/error-handler';
import type { Instrumentation } from 'next';
export function register(): void {
configureErrorHandler({ report: captureServerError });
}
export const onRequestError: Instrumentation.onRequestError = (error, _request, context) => {
handleError(error, { where: 'server', name: context.routePath });
};
```
Where the other calls go, with code, is in [error-handling-code.md](error-handling-code.md): `ErrorFallback` classifies, describes, and handles what reaches a boundary; `showActionError` does the same for actions; the query client's `QueryCache.onError` handles failed refetches.
## Acceptance checklist
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
[ ] referenceId is requestId, else digest
[ ] handleError reports 5xx and logic errors with status, code, requestId, and digest, and nothing else
[ ] handleError never throws, even when report or onForbidden throws
[ ] The lib imports nothing but the HTTP lib: no React, Next.js, TanStack, i18next, or sonner
```

View File

@ -1,378 +0,0 @@
# HTTP lib (`packages/libs/src/http`)
The only way code talks to the network. One `HttpClient` class handles requests (GET, POST, PUT, PATCH, DELETE), file upload and download, request and response interceptors, retry, automatic refresh on 401, abort, and one normalized `HttpError`.
It is framework-agnostic (no React, Next.js, TanStack, i18next, sonner, or zustand imports), runs in the browser and on the server, and is built on native `fetch`, `AbortController`, `AbortSignal.any`, `AbortSignal.timeout`, and `XMLHttpRequest` (uploads only). No axios, ky, or other dependency.
Contents: Structure · Types · API · Root and feature clients · Request pipeline · Body and params · Interceptors · Retry · Refresh token · Abort · Files · Errors · Server side · Usage · Acceptance checklist
## Structure
```
packages/libs/src/http/
├── http-client.ts # HttpClient: config, verbs, request pipeline, extend, abortAll
├── http.ts # the root `http` instance and the createHttpClient factory
├── http-error.ts # HttpError, isHttpError, and normalization of anything thrown or returned
├── interceptors.ts # InterceptorManager; use() returns an eject function
├── retry.ts # shouldRetry, backoff with jitter and Retry-After
├── refresh.ts # single-flight refresh coordinator
├── body.ts # body and query serialization, response parsing
├── upload.ts # XMLHttpRequest transport with upload progress
├── server-http.ts # configureServerHttp; exported only from src/server.ts
├── types.ts
├── constants.ts # defaults, HTTP_ERROR_CODES, header names
└── index.ts
```
- `index.ts` exports `HttpClient`, `createHttpClient`, `http`, `HttpError`, `isHttpError`, `HTTP_ERROR_CODES`, and the types (`HttpClientConfig`, `FeatureHttpConfig`, `RequestOptions`, `HttpResponse`, `UploadOptions`, `UploadProgress`, `DownloadResult`, `RetryConfig`, `RefreshConfig`, `RequestInterceptor`, `ResponseInterceptor`, `ErrorInterceptor`, `HttpErrorCode`).
- `server.ts` exports `configureServerHttp`.
- Import by subpath: `import { http } from '@project/libs/http'` and `import { configureServerHttp } from '@project/libs/server'`.
## Types
A sketch. The implementation may add fields but keeps these names and meanings.
```ts
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
interface HttpClientConfig {
baseUrl: string | (() => string); // a function is read on each request, so env is never read at module load
headers?: Record<string, string>;
timeout?: number | false; // ms per attempt, default 15_000
credentials?: RequestCredentials; // default 'include' (auth is cookie-based)
retry?: RetryConfig | false; // default: enabled with the defaults below
refresh?: RefreshConfig | false; // default: false until bootstrap sets it
getCookieHeader?: () => string | Promise<string>; // server only, set through configureServerHttp
mapErrorBody?: (body: unknown, response: Response) => Partial<HttpErrorShape>; // adapts the back end's error contract
}
interface RetryConfig {
attempts: number; // retries after the first try, default 2 (3 tries at most)
methods: HttpMethod[]; // default ['GET', 'HEAD', 'OPTIONS']
statuses: number[]; // default [408, 429, 502, 503, 504]
networkErrors: boolean; // default true (no response)
baseDelay: number; // default 300 ms
maxDelay: number; // default 5_000 ms
}
interface RefreshConfig {
endpoint: string; // relative to baseUrl or absolute, e.g. '/auth/refresh'
method?: 'POST' | 'GET'; // default 'POST'
shouldRefresh?: (error: HttpError) => boolean; // default: error.status === 401
onFailure?: () => void; // called once per failed refresh, e.g. emit the logout event
}
// What a feature may set in http.extend(). Auth settings are left out, so a feature cannot break them.
type FeatureHttpConfig = Omit<Partial<HttpClientConfig>, 'refresh' | 'credentials' | 'getCookieHeader' | 'retry'> & {
retry?: Partial<RetryConfig> | false; // merged field by field over the root's retry
};
interface RequestOptions {
params?: Record<string, QueryValue | QueryValue[] | null | undefined>;
headers?: Record<string, string>;
signal?: AbortSignal;
timeout?: number | false;
retry?: Partial<RetryConfig> | boolean; // false disables; true or an object opts in (see Retry)
skipRefresh?: boolean; // this request never triggers a refresh
responseType?: 'auto' | 'json' | 'text' | 'blob' | 'arrayBuffer'; // default 'auto'
init?: Omit<RequestInit, 'body' | 'method' | 'headers' | 'signal'>; // passthrough, e.g. keepalive or priority; never Next.js caching options
}
interface HttpResponse<T> {
data: T;
status: number;
headers: Headers;
requestId: string;
}
interface HttpErrorShape {
code: HttpErrorCode | string; // the server's code wins when the body has one
message: string;
status: number; // 0 when there was no response (network, timeout, abort)
fieldErrors?: Record<string, string>; // field path → message, e.g. { 'address.city': '...' }
hint?: string; // how the user can fix it
requestId?: string;
retryAfter?: number; // seconds, from Retry-After on 429 and 503
}
```
## API
- Verbs resolve with the parsed body, typed by the caller (the repository passes its `*ResponseDto`): `get<T>(url, options?)`, `delete<T>(url, options?)`, `post<T>(url, body?, options?)`, `put<T>(url, body?, options?)`, `patch<T>(url, body?, options?)`.
- `request<T>({ method, url, body, ...options })` resolves with `HttpResponse<T>`, for when the caller needs the status, headers, or request id (pagination headers, HEAD requests).
- `upload<T>(url, input, options?)` and `download(url, options?)`: see Files.
- `interceptors.request.use(fn)` and `interceptors.response.use(onSuccess?, onError?)` both return an eject function.
- `configure(partial)`: root client only, at bootstrap (for example to set `baseUrl` and `refresh`). Never after the app has started.
- `extend(config: FeatureHttpConfig)`: returns a feature client. It reads the root's config live (settings made later in bootstrap still apply), runs the root's interceptors before its own, and shares the root's refresh coordinator and abort-all controller.
- `abortAll(reason?)`: browser only. On the root it aborts every in-flight request of every feature (logout); on a feature client, only that feature's requests (leaving its page). New requests work right after.
## Root and feature clients
- **Root:** `http` is created once in `http.ts` with retry on with defaults and refresh off. The app's bootstrap sets its `baseUrl` from the app's env (libs never read env, see [lib-env.md](lib-env.md)), turns on refresh, and registers the shared interceptors. Bootstraps are idempotent, so each interceptor is registered once. A request sent before `baseUrl` is set throws a clear error instead of calling a relative URL.
- **Feature:** every feature has `features/<feature>/http.ts` exporting one client made with `http.extend(...)` and named after the feature (`catalogHttp`, `ordersHttp`). A feature with nothing special still has one: `export const ordersHttp = http.extend({});`. That keeps one shape everywhere, and moving a feature to its own service is a one-line change.
- Only the feature's repositories import its client (`../../http` from a repository folder). The feature's `index.ts` does not export it.
- The root `http` is imported only by feature `http.ts` files, the app's bootstrap (configure and shared interceptors), and the logout action (`abortAll`). Repositories never use the root client directly.
What a feature may set:
| Setting | Example | Merge |
|---|---|---|
| `baseUrl` | Its own service: `() => getEnv().catalogApiUrl` | Replaces the root's |
| `headers` | An API version header only this service needs | By key; the feature wins |
| `timeout` | Reports and exports that need 60 s | Replaces the root's |
| `retry` | Search retries more; payments use `retry: false` | Field by field |
| Feature-only interceptors | Unwrapping an envelope only this service uses | Run after the root's |
| `mapErrorBody` | Only for a back end with a different error contract | Replaces the root's |
A feature never sets `refresh`, `credentials`, or `getCookieHeader`: auth works the same for the whole app, and all clients share one refresh, so two features never refresh at once.
- One-off needs of a single endpoint (a longer timeout, no retry, `skipRefresh`) go in that request's options, not in the feature config.
- Merge order per request: lib defaults → root config → feature config → request options. Headers and retry merge by key; everything else is replaced by the more specific value.
- `createHttpClient(config)` makes an independent client that inherits nothing. Use it only for third-party APIs that don't use the app's auth (a maps provider), in the feature's `http.ts`, with `refresh: false`.
## Request pipeline
1. Merge the config (lib defaults → root → feature → request options). Generate one request id with `crypto.randomUUID()`, kept across retries and the refresh replay, and send it as `X-Request-Id`.
2. Run request interceptors in registration order, root first. They run again on every attempt, so retries and the replay after a refresh get fresh headers.
3. Serialize the body and query params. On the server, add the `Cookie` header from `getCookieHeader()`.
4. Send with one signal combined by `AbortSignal.any` from the caller's `signal`, the per-attempt timeout, the feature client's abort-all controller, and the root's.
5. A non-2xx status or no response is normalized to `HttpError`.
6. If refresh applies, refresh and replay once. The replay doesn't count as a retry attempt.
7. If retry applies, wait and go back to step 2.
8. On success, parse the body, run the `onSuccess` interceptors, and resolve. On failure, run the `onError` interceptors and throw the final `HttpError`.
## Body and params
- A plain object or array is sent as `JSON.stringify` with `Content-Type: application/json`.
- `FormData` is sent as is, and `Content-Type` is never set, so the platform adds the multipart boundary.
- `URLSearchParams`, `Blob`, `File`, `ArrayBuffer`, and strings are sent as is. `undefined` sends no body. GET, HEAD, and DELETE bodies are not supported.
- Query params drop `undefined` and `null`, repeat the key for arrays (`?tag=a&tag=b`), encode with `URLSearchParams`, and merge with any query string already in the URL.
- `responseType: 'auto'`: 204, 205, or an empty body resolves with `undefined`; a JSON content type is parsed; anything else resolves as text. Invalid JSON throws `PARSE_ERROR`.
- Unwrapping a back-end envelope (`{ data, meta }`) is a response interceptor's job: on the root when every service uses it, on the feature client when only that service does. Never in each repository.
## Interceptors
- Request: `(config: RequestConfig) => RequestConfig | Promise<RequestConfig>`. Return a new config; never mutate the argument.
- Response: `onSuccess(response: HttpResponse<unknown>)` returns a response, and `onError(error: HttpError)` returns an `HttpError`. `onError` may change the error but can't turn a failure into a success, so a resolved promise always means success.
- Both run in registration order, root before feature. A throwing interceptor fails the request with `INTERCEPTOR_ERROR`.
- Use them for cross-cutting concerns: `Accept-Language` from the current locale, envelope unwrapping, dev logging, Sentry breadcrumbs (method, URL, status, request id).
- Never put business logic, toasts, navigation, store writes, or per-user module state in them (on the server one client serves every user), and never log cookies or auth headers.
- Shared interceptors are registered on the root in bootstrap; feature-only interceptors in the feature's `http.ts`, right after `extend`. Never in components, models, or repositories.
## Retry
- An attempt is retried when its method is in `retry.methods`, the failure is a network error or a status in `retry.statuses`, attempts are left, and the request wasn't aborted.
- The default methods are idempotent reads. POST and PATCH are never retried by default; a request may opt in with `retry: true` only when it sends an idempotency key the back end honors.
- Delay: exponential backoff with full jitter, `random(0, min(maxDelay, baseDelay * 2 ** attempt))`. When the response has `Retry-After` (seconds or a date), wait that long instead, capped at `maxDelay`. Aborting during the wait rejects at once with `ABORTED`.
- Never retried: 4xx other than 408 and 429, `ABORTED`, `TIMEOUT` on non-idempotent methods, and uploads (the UI offers a retry button).
- On the server the defaults are `attempts: 1` and a shorter timeout (about 5 s), so one slow back end doesn't hold up rendering; the page streams around it.
- TanStack Query must not retry on top: `configs/react-query.ts` sets queries' `retry: false`, and the user retries from the error fallback or the toast ([error-handling.md](error-handling.md#reads)). Otherwise one failure multiplies into attempts × query retries.
## Refresh token
- Auth is cookie-based: the refresh endpoint reads the refresh cookie and the server sets new cookies. The lib never reads or stores tokens.
- Trigger: `shouldRefresh(error)` is true (default: 401), refresh is configured, the request didn't set `skipRefresh`, it isn't the refresh request itself, and it hasn't already been replayed after a refresh.
- Single flight: one refresh at a time for the whole app, because the root and every feature client share one coordinator. Requests that get a 401 while a refresh runs wait for it.
- Stale 401: each successful refresh increments a generation number. A request sent before the latest successful refresh that returns 401 is replayed right away, without another refresh.
- On success, every waiting request is replayed once. A replay that gets 401 again fails with `UNAUTHORIZED` without refreshing again, so there are no loops.
- On failure, every waiting request fails with `UNAUTHORIZED` and `onFailure()` runs once (the app emits its logout event; the auth feature clears the store, and on a page that needs a logged-in user the `AuthGuard` sends the user to login). Later requests try normally, so logging in again works without a reload.
- The refresh request is sent with `skipRefresh: true`, `retry: false`, and the normal timeout, and runs request interceptors like any request.
- Waiting is abortable per request: an aborted waiter rejects with `ABORTED` while the refresh continues for the others.
- In the browser, run the refresh inside `navigator.locks.request('http-refresh', ...)` when available, so two tabs never send the same refresh cookie at once (the back end may rotate and revoke it).
- On the server refresh is disabled. Server requests send no auth cookies (Server side), so the server render never reads or refreshes the session, and a 401 there throws `UNAUTHORIZED` to its boundary.
## Abort
- Per request: pass `signal`. Repositories take an optional last parameter `{ signal?: AbortSignal }` and forward it, so `queryFn: ({ signal }) => productsRepository.list(args, { signal })` cancels stale requests on unmount or key change.
- Timeout: per attempt, from `timeout` (request option → feature → root → default). `timeout: false` disables it. Uploads and downloads default to no timeout; the user cancels them instead.
- Whole app: `http.abortAll()` in the logout action, so no request from the old session finishes after logout. One feature: `catalogHttp.abortAll()`, for example when leaving a page with long-running requests.
- Never call `abortAll` on the server: clients are shared by every user's requests.
- The caller's or abort-all's signal produces `ABORTED`; the timeout produces `TIMEOUT`. Tell them apart by which signal fired, not by the message.
- Aborted requests are never retried, never trigger a refresh, and never call `onFailure`. The UI ignores `ABORTED` errors: no toast, no error state.
## Files
```ts
upload<T>(url: string, input: File | Blob | File[] | FormData, options?: UploadOptions): Promise<T>;
interface UploadOptions extends Omit<RequestOptions, 'responseType'> {
method?: 'POST' | 'PUT' | 'PATCH'; // default 'POST'
fieldName?: string; // default 'file', used when input is a File, Blob, or File[]
fields?: Record<string, string>; // extra form fields sent with the file
onProgress?: (progress: UploadProgress) => void;
}
interface UploadProgress {
loaded: number;
total: number;
percent: number; // integer 0–100
}
download(url: string, options?: DownloadOptions): Promise<DownloadResult>;
interface DownloadOptions extends Omit<RequestOptions, 'responseType'> {
onProgress?: (progress: UploadProgress) => void;
}
interface DownloadResult {
blob: Blob;
fileName?: string;
contentType?: string;
}
```
- `upload` wraps a File, Blob, or File[] in `FormData` under `fieldName` (repeated for arrays) with `fields`. It uses `XMLHttpRequest`, because `fetch` can't report upload progress, and still runs interceptors, sends cookies (`withCredentials`), uses the request id, normalizes errors, and joins the refresh flow (the file is re-sent after a successful refresh). `signal` calls `xhr.abort()`. No automatic retry.
- The UI shows the percentage, file name and size, and a cancel button wired to the signal (see [ui-rules.md](ui-rules.md#file-uploads)).
- `download` uses `fetch`. `fileName` comes from `Content-Disposition` (`filename*` first, then `filename`). Progress is reported while reading the body stream when `Content-Length` is known. Saving the blob (object URL and link click) is a small browser util in `shared/utils`, not in the lib.
- `post(url, formData)` is fine for a small file when the UI needs no progress or cancel.
## Errors
- Every failure from every step is thrown as one `HttpError`: it extends `Error` and has the `HttpErrorShape` fields plus `method`, `url`, and `cause`. The lib throws nothing else.
- `isHttpError(error)` checks a brand such as `Symbol.for('project.http-error')`, not only `instanceof`, because server and client bundles can hold separate copies of the class.
- `toJSON()` returns the plain shape for logs and Sentry.
- `mapErrorBody` reads the error body (default: `code`, `message`, `hint`, and `fieldErrors` or `errors` from a JSON body). Set it once on the root when the back-end contract differs; a feature sets its own only for a back end with a different contract.
- `requestId` is the server's `X-Request-Id` response header when present, otherwise the id the client sent, so even network errors can be traced.
- `retryAfter` is the `Retry-After` header of a 429 or 503 in seconds (a date is converted), so the UI can say how long to wait.
- Server messages pass through as is; the back end localizes them from `Accept-Language`. Messages the lib creates (network, timeout, parse, unknown) are i18n keys such as `errors:http.network`, with a matching hint key, and the UI translates them. The lib never imports i18next.
- The lib never shows errors. The error handler lib decides what each one shows and reports it ([lib-error-handler.md](lib-error-handler.md)): a failed read reaches its error boundary or an empty state, a failed action goes through `applyServerErrors` or `showActionError` (fields, form alert, toast), and the auth feature handles logout ([error-handling.md](error-handling.md)).
| Code | When |
|---|---|
| `NETWORK_ERROR` | No response |
| `TIMEOUT` | The per-attempt timeout fired |
| `ABORTED` | The caller or `abortAll` aborted it |
| `VALIDATION` | 400 or 422 with field errors |
| `BAD_REQUEST` | Other 400 |
| `UNAUTHORIZED` | 401 |
| `FORBIDDEN` | 403 |
| `NOT_FOUND` | 404 |
| `CONFLICT` | 409 |
| `RATE_LIMITED` | 429 |
| `SERVER_ERROR` | 5xx |
| `PARSE_ERROR` | The body couldn't be parsed |
| `INTERCEPTOR_ERROR` | An interceptor threw |
| `UNKNOWN` | Anything else |
## Server side
- `bootstrap.server.ts` calls `configureServerHttp` once (code below). It sets the root's server `baseUrl` (from the app's server env, for example an internal service address) and the cookie provider on the root, so every feature client forwards the same cookies. A feature with its own `baseUrl` reads it through its project's `getEnv()`, which the server bootstrap fills with the server-side address.
- `getCookieHeader` runs on every server request and forwards only the names in the app's `FORWARDED_COOKIES`, the cookies the server render needs, such as `THEME_COOKIE`. An indexable page's locale comes from its URL, never from a forwarded cookie ([ui-rules.md](ui-rules.md#crawlers)). In an app with more than one locale, the page passes its URL's locale to its cache calls, and the repository sends it as the back-end request's `Accept-Language` header, in that request's `headers` option. The server registers no `Accept-Language` interceptor: an interceptor never sees the URL, and a module-level language would serve every request. It never forwards the auth cookies, so no back-end response on the server depends on who the viewer is ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). Never keep cookies, users, or tokens in module state.
- On the server, refresh is off, `abortAll` is unavailable, retry defaults to one attempt with a shorter timeout, `credentials` is ignored, and every request is sent with `cache: 'no-store'`, whatever `init` says.
- `init` never carries Next.js caching options (`next: { revalidate, tags }`): the Next.js server keeps no cache between requests (see [b2c-b2b.md](b2c-b2b.md#no-server-cache)).
`bootstrap.server.ts`:
```ts
configureServerHttp({
baseUrl: serverEnv.API_INTERNAL_URL,
getCookieHeader: async () =>
(await cookies())
.getAll()
.filter(({ name }) => FORWARDED_COOKIES.has(name))
.map(({ name, value }) => `${name}=${encodeURIComponent(value)}`)
.join('; '),
});
```
`FORWARDED_COOKIES` is a `ReadonlySet<string>` in the app's `constants/`, built from the cookie name constants ([lib-cookie.md](lib-cookie.md)). Adding an auth cookie to it is an override of rendering-patterns.md's Auth-dependent UI rule and needs a recorded decision.
## Usage
`features/catalog/http.ts`. `getEnv` is the owning project's env getter (see [lib-env.md](lib-env.md#project-env)).
```ts
import { http } from '@project/libs/http';
import { getEnv } from '../../env';
export const catalogHttp = http.extend({
baseUrl: () => getEnv().catalogApiUrl,
timeout: 30_000,
retry: { attempts: 3 },
});
catalogHttp.interceptors.response.use((response) => ({
...response,
data: (response.data as CatalogEnvelope).result,
}));
```
`features/orders/http.ts`, a feature with nothing special:
```ts
import { http } from '@project/libs/http';
export const ordersHttp = http.extend({});
```
`features/catalog/repositories/products/products.ts`
```ts
import type { DownloadResult, UploadProgress } from '@project/libs/http';
import { catalogHttp } from '../../http';
export const productsRepository = {
async list(args: ListProductsArgs, options?: { signal?: AbortSignal }): Promise<ListProductsPayload> {
const response = await catalogHttp.get<ListProductsResponseDto>(PRODUCTS_ENDPOINT, {
params: toListProductsParams(args),
signal: options?.signal,
});
return toListProductsPayload(response);
},
async uploadImage(
args: UploadProductImageArgs,
options?: { signal?: AbortSignal; onProgress?: (progress: UploadProgress) => void },
): Promise<ProductImagePayload> {
const response = await catalogHttp.upload<UploadImageResponseDto>(
productImageEndpoint(args.productId),
args.file,
options,
);
return toProductImagePayload(response);
},
exportReport(args: ExportProductsArgs): Promise<DownloadResult> {
return catalogHttp.download(PRODUCTS_EXPORT_ENDPOINT, { params: toExportParams(args), timeout: 120_000 });
},
};
```
The export's long timeout applies to that one request, so it is a request option, not feature config.
Bootstrap, root client only (`bootstrap.client.ts`). The refresh endpoint and logout event come from the auth feature's public API.
```ts
http.configure({
baseUrl: clientEnv.NEXT_PUBLIC_API_URL,
refresh: { endpoint: AUTH_ENDPOINTS.refresh, onFailure: () => eventEmitter.emit(AUTH_EVENTS.logout) },
});
http.interceptors.request.use((config) => ({
...config,
headers: { ...config.headers, 'Accept-Language': i18n.language },
}));
```
## Acceptance checklist
For building or changing the lib:
```
[ ] GET, POST, PUT, PATCH, DELETE send the right method, headers, JSON or FormData body, and query params, and resolve with the parsed body
[ ] A request sent before bootstrap sets the root's baseUrl throws a clear "not configured" error
[ ] 204 resolves with undefined; invalid JSON throws PARSE_ERROR
[ ] Request and response interceptors run in order, re-run on retry and replay, and eject works
[ ] A GET that gets 503 twice then 200 resolves after 3 tries; a POST that gets 503 fails at once
[ ] Retry-After is respected; aborting during the backoff wait rejects at once with ABORTED
[ ] Five parallel requests that all get 401 cause exactly one refresh, then all five replay and resolve, also across feature clients
[ ] http.extend rejects refresh, credentials, and getCookieHeader at type level; feature headers and retry merge over the root's; request options win over both
[ ] A feature client runs the root's interceptors before its own and sees root settings made after it was created
[ ] A failed refresh rejects all waiters with UNAUTHORIZED and calls onFailure exactly once
[ ] A replay that gets 401 again fails without a second refresh
[ ] Caller abort gives ABORTED and timeout gives TIMEOUT; http.abortAll() aborts every feature's requests, a feature's abortAll() only its own, and new requests still work
[ ] Upload reports progress from 0 to 100, can be cancelled, and joins the refresh flow
[ ] Download returns the blob and the file name from Content-Disposition
[ ] Every failure is an HttpError with code, message, status, fieldErrors, hint, and requestId, plus retryAfter on a 429 or 503 that sends Retry-After; isHttpError works across bundles
[ ] On the server, each request forwards only its own allowed cookies and never the auth cookies, is sent with cache: 'no-store', refresh never runs, and no state leaks between requests
```

File diff suppressed because it is too large Load Diff

View File

@ -1,111 +0,0 @@
# Local-storage lib (`packages/libs/src/local-storage`)
One `LocalStorageAdapter` class over `window.localStorage` that puts every key under the app's prefix (`shop.cart`), so apps and third-party scripts on the same origin never overwrite each other. It implements the native `Storage` interface, so it drops into anything that expects `localStorage`, including zustand's `createJSONStorage`. Browser only; framework-agnostic; no dependency.
Contents: What local storage is for · Structure · API · Keys · Blocked storage · Browser only · Persisted zustand stores · Usage · Acceptance checklist
## What local storage is for
- Client-only data that should survive a reload and that the server never needs: UI preferences (table page size, collapsed sidebar), form drafts, recently viewed items, the last used phone number, persisted zustand stores.
- Data the server needs while rendering goes in a cookie ([lib-cookie.md](lib-cookie.md)). Server state goes in the TanStack Query cache, not here.
- Never tokens, secrets, or personal data that would hurt if leaked: any script on the page, including an XSS payload, can read local storage. Auth uses HttpOnly cookies ([lib-http.md](lib-http.md)).
- About 5 MB per origin, shared by every app on it. Keep values small and never cache large API responses here.
## Structure
```
packages/libs/src/local-storage/
├── local-storage.ts # LocalStorageAdapter class and the shared `storage` instance
├── types.ts # LocalStorageOptions
├── constants.ts # DEFAULT_STORAGE_PREFIX, STORAGE_KEY_SEPARATOR ('.')
└── index.ts
```
- `index.ts` exports `LocalStorageAdapter`, `storage`, `DEFAULT_STORAGE_PREFIX`, and the type `LocalStorageOptions`. Nothing goes in `server.ts`: the lib is browser-only.
- Import by subpath: `import { storage } from '@project/libs/local-storage'`.
- The instance is named `storage`, never `localStorage`, so it never shadows the global.
## API
```ts
interface LocalStorageOptions {
prefix: string; // the app's namespace, e.g. 'shop'; default DEFAULT_STORAGE_PREFIX
}
```
- Every key a caller passes is stored as `<prefix>.<key>`. Callers always use the short key; only the adapter knows the full one.
- `getItem(key)` returns the value or `null`; `setItem(key, value)` stores a string; `removeItem(key)` removes one key.
- The rest of `Storage` works inside the prefix only, so the adapter behaves like its own storage:
- `length` counts the keys under the prefix.
- `key(index)` returns the short key at that index among the prefixed keys, or `null`.
- `clear()` removes only the keys under the prefix. It never calls `window.localStorage.clear()`, which would delete other apps' and libraries' data.
- `clearByPrefix(subPrefix)` removes every key under `<prefix>.<subPrefix>`, for example `storage.clearByPrefix('session.')` on logout. Collect the matching keys first, then remove them, because removing while iterating shifts the indexes.
- `getJSON<T>(key)` parses the stored JSON and returns `null` for a missing key or invalid JSON (removing the broken value). The result is untrusted, since the data may be old or edited by the user, so callers that depend on its shape validate it with a valibot schema.
- `setJSON(key, value)` runs `JSON.stringify`, then `setItem`.
- `configure(options: LocalStorageOptions)` sets the prefix once, in the app's bootstrap. It only stores options and never touches `window`, so it's safe in `bootstrap.client.ts` during SSR. Changing a prefix later leaves the old keys behind, so pick it once per app.
- The shared instance is `export const storage = new LocalStorageAdapter();`. Create another `LocalStorageAdapter` only in tests.
## Keys
- Keys are constants in the owning project's `constants.ts` (`LAST_PHONE_STORAGE_KEY` in the auth feature), never string literals at call sites.
- Group keys by lifetime with a sub-prefix. `session.*` holds data that belongs to the logged-in user (drafts, recent items), and the logout action clears it with `storage.clearByPrefix('session.')`. Other keys are device preferences that survive logout.
- When the shape of a stored value changes, change the key (`cart.v2`) or use zustand persist's `version` and `migrate`, and remove the old key, so old data never breaks new code.
- Data written through the adapter isn't readable with `window.localStorage.getItem(key)` and the short key. Always read it back through `storage`.
## Blocked storage
- Browsers can block or limit storage: Safari private mode, storage disabled by the user or a policy, or a full quota. Access then throws `SecurityError` or `QuotaExceededError`.
- The adapter catches these: `getItem` returns `null`, `setItem` and `removeItem` do nothing, and a warning is logged in development only. Persisted data is a convenience, so the app keeps working without it.
- Features never depend on local storage for correctness. Anything that must not be lost goes to the server.
## Browser only
- Every method except `configure` checks `typeof window === 'undefined'` and throws a clear error ("storage is browser-only; never read it during render or on the server") instead of the unclear "window is not defined". Server access is a programming mistake, so it throws; blocked storage is the user's environment, so it's handled quietly.
- Call it only in event handlers, effects, actions, and client bootstrap code. Never during render and never at module top level: client components also render on the server, and a value read during render differs between server and browser, which breaks hydration.
- Repositories never use it, so they stay server-safe.
## Persisted zustand stores
- Use the adapter as the storage: `persist(creator, { name: 'cart', storage: createJSONStorage(() => storage), version: 1, migrate })`. The name becomes the key, stored as `<prefix>.cart`; put it under `session.` when it belongs to the logged-in user.
- Persist only what must survive a reload, with `partialize`. Never loading flags or server data.
- Set `skipHydration: true` and call `useCartStore.persist.rehydrate()` in an effect of the platform's `AppShell`, so the server render and the first browser render match. Stores are never written during server render, so storage is never touched on the server.
Code: [code-patterns.md](code-patterns.md#persisted-store).
## Usage
Bootstrap (`bootstrap.client.ts`):
```ts
storage.configure({ prefix: 'shop' });
```
A model reading a preference in an effect, `features/catalog/models/products/use-products-page.ts`:
```ts
useEffect(() => {
const stored = storage.getJSON<number>(PRODUCTS_PAGE_SIZE_STORAGE_KEY);
if (stored !== null && PAGE_SIZES.includes(stored)) setPageSize(stored);
}, []);
```
The logout action:
```ts
storage.clearByPrefix(SESSION_STORAGE_PREFIX); // 'session.'
```
## Acceptance checklist
For building or changing the lib:
```
[ ] setItem('token', 'abc') writes '<prefix>.token'; getItem('token') reads it; window.localStorage.getItem('token') is null
[ ] removeItem removes only the prefixed key
[ ] length, key(index), and clear work inside the prefix only; keys of other prefixes and unprefixed keys survive clear
[ ] clearByPrefix('session.') removes every '<prefix>.session.*' key and nothing else
[ ] getJSON returns the parsed value, and null (removing the value) for a missing key or invalid JSON
[ ] With storage blocked or full, getItem returns null and setItem doesn't throw
[ ] Every method except configure throws the clear browser-only error on the server
[ ] zustand createJSONStorage(() => storage) persists and rehydrates a store under '<prefix>.<name>'
```

View File

@ -1,678 +0,0 @@
# PWA lib (`packages/libs/src/pwa`)
Makes each app an installable PWA, with a splash screen on Android and iOS, 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 only 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 · Splash screens · Not in this lib · Implementation · Usage · Acceptance checklist
## What the worker stores
| Kind | URL | Strategy | Why a stored copy stays correct |
|---|---|---|---|
| JS and CSS, content-hashed | `/_next/static/{chunks,css,immutable}/**/*.{js,css}` | Cache first | Next.js names each file by a hash of its content, so a path never changes content |
| Other JS and CSS | The rest of `/_next/static/**/*.{js,css}`, such as `/_next/static/<buildId>/_buildManifest.js` | Stale-while-revalidate | No content hash: the path stays while the content changes (since Next.js 16.2 the build ID is one constant when a deployment ID is set) |
| Fonts | `/fonts/*.woff2` | Stale-while-revalidate | 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>` | Stale-while-revalidate | 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.
- The kind picks the strategy; no app or option changes it. Changing a kind's strategy changes the lib and needs a recorded decision ([decisions.md](decisions.md)).
- Cache first, for content-hashed JS and CSS: a stored file is served with no network request at all. A miss goes to the network, and the response is stored for the next request. These are every chunk and stylesheet an App Router page loads. A release never changes a file under its path, so a check could never find a newer file; it would only cost a request.
- Content-hashed files are stored and found by origin and path, without the query string. Next.js adds `?dpl=<deployment ID>` to them, which changes on every release ([b2c-b2b.md](b2c-b2b.md#deploys-and-version-skew)), but the hash in the path already names the content. So a chunk that didn't change between releases still comes from the device after a deploy, and each file is stored once. With Turbopack, the Next.js 16 default, chunks don't depend on the deployment ID; webpack writes the ID into some chunks, so those get new names on every release. The worker builds that key itself instead of matching with `ignoreSearch`, which makes Chromium scan every entry.
- Stale-while-revalidate, for every other stored file, by the exact URL with its query string: 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.
- Why the rest still checks: their paths don't name their content. People keep the names and versions of fonts and the sprite, not a build step. A font changed under its old name, or a sprite change without a version bump, breaks the rules, and the background check heals it after one visit. The check costs little: the files are immutable under their URLs, so the HTTP cache answers almost every one.
- `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-v2`. 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
├── splash-screens.ts # APPLE_STARTUP_IMAGES: one iOS startup image per device size and orientation
├── 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, CacheLoadedMessage, ServiceWorkerPluginOptions, AppleDevice, AppleStartupImage
├── constants.ts # SERVICE_WORKER_URL, SERVICE_WORKER_SCOPE, CACHE_NAME_PREFIX, SERVICE_WORKER_CONFIG, SERVICE_WORKER_HEADERS, APPLE_DEVICES, APPLE_SPLASH_DIR
├── 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`, `APPLE_STARTUP_IMAGES`, and the types `ServiceWorkerOptions`, `ServiceWorkerConfig`, and `AppleStartupImage`. It runs nothing at import, so `bootstrap.client.ts` can import it during SSR, and the root layout can read `APPLE_STARTUP_IMAGES`. Nothing goes in `server.ts`.
- `plugin.ts` exports `writeServiceWorker`, `SERVICE_WORKER_URL`, `SERVICE_WORKER_HEADERS`, and the type `ServiceWorkerPluginOptions`, 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
};
// The worker's settings. writeServiceWorker writes them into public/sw.js; the worker reads nothing else.
type ServiceWorkerConfig = {
cacheName: string; // the one cache, e.g. 'pwa-assets-v2'
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
hashed: readonly string[]; // static folders whose names are content hashes: cache first, keyed by path
fonts: string; // '/fonts/': .woff2 only; stale-while-revalidate
sprite: string; // '/icons/symbol-defs.svg', stored with its ?v=<N>; stale-while-revalidate
};
};
// 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/
};
// One iOS screen size, in CSS pixels, portrait.
type AppleDevice = {
width: number; // device-width
height: number; // device-height
ratio: number; // -webkit-device-pixel-ratio
};
// One startup image: Next.js's appleWebApp.startupImage takes { url, media }; the generator also needs the pixel size.
type AppleStartupImage = {
url: string; // e.g. '/pwa/splash/apple-splash-1290x2796.png'
media: string; // the device-width, device-height, pixel ratio, and orientation it matches
width: number; // image pixels
height: number;
};
```
## 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 })` compiles `service-worker.ts` with the workspace's own `typescript` (`transpileModule`; no new dependency), writes `SERVICE_WORKER_CONFIG` above it, 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.
- Content-hashed `/_next/static/` JS and CSS: cache first, keyed by path.
- Other `/_next/static/` JS and CSS, fonts, and the sprite: stale-while-revalidate, keyed by exact URL.
- 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 stored 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 version in `SERVICE_WORKER_CONFIG.cacheName` (`v2`) 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 a kind's strategy changes `sw.js`, so it reaches visitors like any other worker update. It also changes how the worker keys that kind (cache first by path, stale-while-revalidate by exact URL), so raise the `cacheName` version in the same change.
- 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 two thirds, which the Android 12 splash keeps (the maskable safe zone alone is 80%). No icon has `sizes: 'any'`, such as a `favicon.ico` entry: Chrome would pick it for the splash over the PNGs. `app/apple-icon.png` (180×180) covers iOS. The worker doesn't store them, because they're images.
## Splash screens
An installed app shows a splash screen while it starts. Both platforms show the logo centered on the manifest's `background_color`, so they look the same.
- Android builds it from the manifest; there is no way to ship a splash image. Chrome fills the screen with `background_color` (light grey `#F8F9FA` without one) and centers the `maskable` icon, or an `any` icon when there is no maskable one. Android 12 and later draw it masked in a 240dp box with no name; earlier versions add `name` below it. `theme_color` colors the status bar. So `background_color` is opaque and matches the page surface of the first paint.
- iOS shows the `apple-touch-startup-image` whose `media` matches the device. With no match it shows a blank screen, as it does on an iPhone with Display Zoom or an iPad in Split View, whose sizes no table lists. The root layout's metadata includes `APPLE_WEB_APP` from `configs/pwa.ts`: `appleWebApp.startupImage` lists `APPLE_STARTUP_IMAGES` from this lib, and `other` adds `<meta name="apple-mobile-web-app-capable" content="yes">`. iOS shows startup images only with that tag, and since 15.0 Next.js renders `appleWebApp.capable` only as `mobile-web-app-capable`, which iOS doesn't read.
- `APPLE_DEVICES` lists each distinct iPhone and iPad screen: its CSS width and height in portrait and its pixel ratio. `APPLE_STARTUP_IMAGES` turns each into a portrait and a landscape image, `/pwa/splash/apple-splash-<width>x<height>.png` in pixels. In landscape, `device-width` and `device-height` keep their portrait values and only `orientation` changes.
- Each media query tests `device-height` only when width and pixel ratio don't already identify the screen (the 834px iPads). On iOS 27.0.1, a query that tests `device-height` never matches (WebKit bug 326500), and those devices start on a blank screen.
- The images are PNG files in `public/pwa/splash/`, committed, never `data:` URLs, which iOS 17.6 and later ignore. Root `tools/generate-splash-screens.ts` writes them with `ImageResponse` from `next/og`, which Next.js already ships, so no dependency is added (Usage). Run it again when the logo, `background_color`, or `APPLE_DEVICES` changes.
- iOS picks the image when the visitor adds the app to the Home Screen. A changed image reaches only later installs, and a later switch to dark mode keeps the light image, so there are no dark images.
- When Apple ships a new screen size, add it to `APPLE_DEVICES` and run the generator. Apple no longer publishes a size table, so take the pixel size from the device's spec page and divide it by its pixel ratio.
- The worker doesn't store the images: iOS reads them once, at install.
## 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 |
| Android splash images | No manifest field exists for them; Chrome builds the splash from the manifest |
| Dark iOS startup images | iOS picks the image at install and keeps it after a theme switch |
## Implementation
`constants.ts`
```ts
import type { AppleDevice, 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 = {
cacheName: `${CACHE_NAME_PREFIX}assets-v2`, // raise the version when the worker changes what it stores or how it keys it
cachePrefix: CACHE_NAME_PREFIX,
maxEntries: 200,
cacheLoadedMessage: 'pwa.cache-loaded',
paths: {
static: '/_next/static/',
hashed: ['/_next/static/chunks/', '/_next/static/css/', '/_next/static/immutable/'],
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'",
};
export const APPLE_SPLASH_DIR = '/pwa/splash';
// Each distinct iOS screen: CSS width and height in portrait, and the pixel ratio.
// Add a new size from the device's spec page: pixels divided by the ratio.
export const APPLE_DEVICES: readonly AppleDevice[] = [
{ width: 440, height: 956, ratio: 3 }, // iPhone 16 Pro Max, 17 Pro Max, 18 Pro Max
{ width: 430, height: 932, ratio: 3 }, // iPhone 14 Pro Max, 15 Plus, 15 Pro Max, 16 Plus
{ width: 428, height: 926, ratio: 3 }, // iPhone 12 Pro Max, 13 Pro Max, 14 Plus
{ width: 420, height: 912, ratio: 3 }, // iPhone Air
{ width: 414, height: 896, ratio: 3 }, // iPhone XS Max, 11 Pro Max
{ width: 414, height: 896, ratio: 2 }, // iPhone XR, 11
{ width: 402, height: 874, ratio: 3 }, // iPhone 16 Pro, 17, 17 Pro, 18 Pro
{ width: 393, height: 852, ratio: 3 }, // iPhone 14 Pro, 15, 15 Pro, 16
{ width: 390, height: 844, ratio: 3 }, // iPhone 12, 12 Pro, 13, 13 Pro, 14, 16e, 17e
{ width: 375, height: 812, ratio: 3 }, // iPhone X, XS, 11 Pro, 12 mini, 13 mini
{ width: 375, height: 667, ratio: 2 }, // iPhone 8, SE 2nd and 3rd gen
{ width: 1032, height: 1376, ratio: 2 }, // iPad Pro 13" (M4, M5)
{ width: 1024, height: 1366, ratio: 2 }, // iPad Pro 12.9", iPad Air 13"
{ width: 834, height: 1210, ratio: 2 }, // iPad Pro 11" (M4, M5)
{ width: 834, height: 1194, ratio: 2 }, // iPad Pro 11" (1st to 4th gen)
{ width: 834, height: 1112, ratio: 2 }, // iPad Air 10.5", iPad Pro 10.5"
{ width: 820, height: 1180, ratio: 2 }, // iPad Air 10.9" and 11", iPad 10th gen, iPad (A16)
{ width: 810, height: 1080, ratio: 2 }, // iPad 10.2" (7th to 9th gen)
{ width: 768, height: 1024, ratio: 2 }, // iPad 9.7", iPad mini 5
{ width: 744, height: 1133, ratio: 2 }, // iPad mini 6, iPad mini (A17 Pro)
];
```
`splash-screens.ts`
```ts
import { APPLE_DEVICES, APPLE_SPLASH_DIR } from './constants';
import type { AppleDevice, AppleStartupImage } from './types';
// device-height only where width and ratio don't identify the screen: on iOS 27.0.1 it never matches (WebKit bug 326500).
function needsHeight({ width, ratio }: AppleDevice): boolean {
return APPLE_DEVICES.filter((device) => device.width === width && device.ratio === ratio).length > 1;
}
function toStartupImage(device: AppleDevice, orientation: 'portrait' | 'landscape'): AppleStartupImage {
const { width, height, ratio } = device;
// In landscape the image turns, but device-width and device-height keep their portrait values.
const [pixelWidth, pixelHeight] =
orientation === 'portrait' ? [width * ratio, height * ratio] : [height * ratio, width * ratio];
const media = [
`(device-width: ${width}px)`,
...(needsHeight(device) ? [`(device-height: ${height}px)`] : []),
`(-webkit-device-pixel-ratio: ${ratio})`,
`(orientation: ${orientation})`,
].join(' and ');
return {
url: `${APPLE_SPLASH_DIR}/apple-splash-${pixelWidth}x${pixelHeight}.png`,
media,
width: pixelWidth,
height: pixelHeight,
};
}
export const APPLE_STARTUP_IMAGES: readonly AppleStartupImage[] = APPLE_DEVICES.flatMap((device) => [
toStartupImage(device, 'portrait'),
toStartupImage(device, 'landscape'),
]);
```
`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 { cacheName, cachePrefix, maxEntries, cacheLoadedMessage, paths } = SERVICE_WORKER_CONFIG;
function isStatic({ pathname }: URL): boolean {
return pathname.startsWith(paths.static) && (pathname.endsWith('.js') || pathname.endsWith('.css'));
}
// A content hash in the path names the file, so it is served cache first and keyed without its ?dpl=.
function isHashed(url: URL): boolean {
return isStatic(url) && paths.hashed.some((folder) => url.pathname.startsWith(folder));
}
function isStoredKind(url: URL): boolean {
if (url.origin !== worker.location.origin) return false;
const { pathname } = url;
if (isStatic(url)) return true;
if (pathname.startsWith(paths.fonts)) return pathname.endsWith('.woff2');
return pathname === paths.sprite;
}
function cacheKey(request: Request): Request | string {
const url = new URL(request.url);
return isHashed(url) ? url.origin + url.pathname : request;
}
function findStored(request: Request): Promise<Response | undefined> {
return caches.match(cacheKey(request), { cacheName, ignoreVary: true });
}
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(cacheKey(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 findStored(event.request);
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> {
return (await findStored(event.request)) ?? fromNetwork(event);
}
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) => {
const request = new Request(url.href);
if (await findStored(request)) return;
// The page loaded it a moment ago, so the HTTP cache answers.
const response = await fetch(request).catch(() => null);
if (response && isStorable(response)) await store(request, 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;
const url = new URL(request.url);
if (!isStoredKind(url)) return;
// A content-hashed file never changes under its path, so a check would only cost a request.
event.respondWith(isHashed(url) ? cacheFirst(event) : staleWhileRevalidate(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 }: 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 script = `const SERVICE_WORKER_CONFIG = ${JSON.stringify(SERVICE_WORKER_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.
```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`. `APPLE_WEB_APP` goes into the root layout's metadata.
```ts
import { APPLE_STARTUP_IMAGES } from '@project/libs/pwa';
import type { Metadata, 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;
// iOS: startup images, and the Apple tag that Next.js's appleWebApp.capable no longer renders.
export const APPLE_WEB_APP = {
appleWebApp: {
capable: true,
statusBarStyle: 'default',
startupImage: APPLE_STARTUP_IMAGES.map(({ url, media }) => ({ url, media })),
},
other: { 'apple-mobile-web-app-capable': 'yes' },
} satisfies Metadata;
```
`apps/<app>/src/app/layout.tsx`, part of the root layout. Its metadata is fixed, so it's the `metadata` export; a root layout whose title follows the locale spreads `APPLE_WEB_APP` into `generateMetadata` instead.
```ts
import type { Metadata } from 'next';
import { APPLE_WEB_APP } from '../configs';
export const metadata: Metadata = {
...APPLE_WEB_APP,
};
```
`tools/generate-splash-screens.ts`, the root script that writes an app's startup images. Run it with jiti from the repo root: `jiti tools/generate-splash-screens.ts apps/<app> <square-logo.svg>`. `next`, `react`, and `@project/libs/pwa` must resolve from `tools/`: under pnpm, `next` and `react` are root dependencies, and a workspace that maps `@project/*` only with `tsconfig.base.json` paths passes the alias as an absolute path, `JITI_ALIAS='{"@project/libs":"<repo-root>/packages/libs/src"}'`. Type-check `tools/` with the DOM lib, because `@project/libs/pwa` also exports the page side. Convert any text in the logo to paths: the renderer draws SVG text in a fallback font.
```ts
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { ImageResponse } from 'next/og';
import { createElement } from 'react';
import { APPLE_STARTUP_IMAGES } from '@project/libs/pwa';
async function main(): Promise<void> {
const [appDir, logoFile] = process.argv.slice(2);
if (!appDir || !logoFile) throw new Error('Usage: jiti tools/generate-splash-screens.ts apps/<app> <square-logo.svg>');
// The same background_color as the manifest, so Android and iOS match.
const { PWA_MANIFEST } = await import(path.resolve(appDir, 'src/configs/pwa.ts'));
const logo = `data:image/svg+xml;base64,${readFileSync(logoFile).toString('base64')}`;
for (const { url, width, height } of APPLE_STARTUP_IMAGES) {
const size = Math.round(Math.min(width, height) / 4);
const page = createElement(
'div',
{
style: {
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: PWA_MANIFEST.background_color,
},
},
createElement('img', { src: logo, width: size, height: size }),
);
const image = new ImageResponse(page, { width, height });
const file = path.join(appDir, 'public', url);
mkdirSync(path.dirname(file), { recursive: true });
writeFileSync(file, Buffer.from(await image.arrayBuffer()));
}
}
main().catch((error: unknown) => {
console.error(error);
process.exitCode = 1;
});
```
`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
[ ] A stored file from /_next/static/chunks/, css/, or immutable/ is served with no network request at all, also answers the same path with a different ?dpl=, and is stored once per path
[ ] Each other served file (/_next/static/<buildId>/ files, fonts, the sprite) 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
[ ] 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
[ ] APPLE_STARTUP_IMAGES has a portrait and a landscape image for every APPLE_DEVICES entry, and its media tests device-height only for screens that share width and pixel ratio
[ ] Every startup image exists in public/pwa/splash/ with exactly its pixel size, and the root layout renders apple-mobile-web-app-capable and one apple-touch-startup-image link per image in <head>
[ ] Installed from the Home Screen, an iPhone and an iPad open on the splash image; an Android phone opens on background_color with the maskable icon
```

View File

@ -1,246 +0,0 @@
# 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 with its status and 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. The page's rendering doc comes first ([page-rendering.md](page-rendering.md#writing-a-doc)).
`platforms/<platform>/src/shared/utils/get-device.ts`
```ts
import 'server-only';
import { headers } from 'next/headers';
import { userAgent } from 'next/server';
export type Device = 'mobile' | 'desktop';
// By device class only, never by isBot: content that differs for crawlers is cloaking.
// Googlebot Smartphone parses as 'mobile', so Google indexes the mobile template; tablets get desktop.
export function deviceFromHeaders(requestHeaders: Headers): Device {
return userAgent({ headers: requestHeaders }).device.type === 'mobile' ? 'mobile' : 'desktop';
}
export async function getDevice(): Promise<Device> {
return deviceFromHeaders(await headers());
}
```
Where the repo has a unit test runner, `get-device.test.ts` pins the mapping, so a parser upgrade can't send Googlebot Smartphone to the desktop template; otherwise the PR proposes the runner, which needs approval ([refactoring.md](refactoring.md#when-and-how)). The test setup maps `server-only` to an empty module, as it does for every server-only test.
```ts
import { deviceFromHeaders } from './get-device';
const GOOGLEBOT_SMARTPHONE =
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.122 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
const GOOGLEBOT_DESKTOP =
'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Chrome/141.0.7390.122 Safari/537.36';
describe('deviceFromHeaders', () => {
it('sends Googlebot Smartphone to the mobile template, which Google indexes', () => {
expect(deviceFromHeaders(new Headers({ 'user-agent': GOOGLEBOT_SMARTPHONE }))).toBe('mobile');
});
it('sends Googlebot Desktop and requests without a User-Agent to the desktop template', () => {
expect(deviceFromHeaders(new Headers({ 'user-agent': GOOGLEBOT_DESKTOP }))).toBe('desktop');
expect(deviceFromHeaders(new Headers())).toBe('desktop');
});
});
```
`platforms/<platform>/src/features/catalog/caches/products.ts`
```ts
import 'server-only';
import { cache } from 'react';
import { productsRepository } from '../repositories/products';
import { RELATED_PRODUCTS_LIMIT } from './constants';
export const getProduct = cache((id: string) => productsRepository.get({ id }));
export const getRelatedProducts = cache((id: string) =>
productsRepository.listRelated({ id, limit: RELATED_PRODUCTS_LIMIT }),
);
export const getProductReviews = cache((id: string, page: number) => productsRepository.listReviews({ id, page }));
```
`platforms/<platform>/src/features/catalog/caches/server.ts`
```ts
import 'server-only';
export { getProduct, getProductReviews, getRelatedProducts } from './products';
```
`platforms/<platform>/src/server.ts`
```ts
import 'server-only';
export { readOnServer } from './app/error-boundaries/read-on-server/server';
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`. A product page is an entity page: no `loading.tsx` sits above it, so its status is decided before the first byte ([error-handling.md](error-handling.md#b2cb2b-server)). `generateMetadata` and the page both call `readProduct`, which reads `getProduct(id)` through `readOnServer`, and the cache sends one request. A missing product answers 404, and a replaced one 308 to its replacement; `replacedBy` stands for the id of the product that replaces this one, which the back end sends. The page renders its JSON-LD from the same product, for an `ok` read only, before the template and in the first flush; `buildProductPageJsonLd` is in [lib-json-ld.md](lib-json-ld.md#usage). The seller page in [error-handling-code.md](error-handling-code.md#server-reads) has the same shape and explains the narrowing.
```tsx
import { JsonLd } from '@project/island/primitives/json-ld/server';
import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { paths } from '@project/<platform>/app/navigation';
import { buildProductPageJsonLd, getDevice, getProduct, readOnServer } from '@project/<platform>/server';
import type { Metadata } from 'next';
import { notFound, permanentRedirect } from 'next/navigation';
import { ProductDesktop } from './templates/product-desktop';
import { ProductMobile } from './templates/product-mobile';
type ProductPageProps = { params: Promise<{ id: string }> };
// Throws for a missing or replaced product; returns 'ok' or 'no-access'.
async function readProduct(id: string) {
const product = await readOnServer(() => getProduct(id));
if (product.status === 'not-found') notFound();
if (product.status === 'ok' && product.data.replacedBy) permanentRedirect(paths.product(product.data.replacedBy));
return product;
}
export async function generateMetadata({ params }: ProductPageProps): Promise<Metadata> {
const { id } = await params;
const product = await readProduct(id);
if (product.status !== 'ok') return { robots: { index: false } };
return {
title: product.data.name,
description: product.data.summary,
alternates: { canonical: paths.product(product.data.id) },
};
}
export default async function ProductPage({ params }: ProductPageProps) {
const { id } = await params;
const [device, product] = await Promise.all([getDevice(), readProduct(id)]);
if (product.status !== 'ok') return <StatusEmptyState variant={product.status} size="page" />;
return (
<>
<JsonLd data={buildProductPageJsonLd(product.data)} />
{device === 'mobile' ? <ProductMobile product={product.data} /> : <ProductDesktop product={product.data} />}
</>
);
}
```
Every link to a product page, like every link to an indexable page, is the platform's `NavLink`, which shows a pending hint while the page loads, because the page has no `loading.tsx` to show at once ([rendering-patterns.md](rendering-patterns.md#loading-patterns)).
The desktop template, a Server Component, renders the product at once and streams the two slower parts, each behind its own part boundary ([error-handling.md](error-handling.md#boundaries)):
```tsx
<ProductSummary product={product} />
<PartBoundary name="related-products">
<Suspense fallback={<RelatedProductsSkeleton />}>
<RelatedProducts productId={product.id} />
</Suspense>
</PartBoundary>
<PartBoundary name="product-reviews">
<Suspense fallback={<ProductReviewsSkeleton />}>
<ProductReviews productId={product.id} />
</Suspense>
</PartBoundary>
```
`.../product/[id]/organisms/related-products/RelatedProducts.tsx`. The client only shows this part, so it stays a Server Component.
```tsx
import { NavLink } from '@project/<platform>/app/navigation';
import { getRelatedProducts } from '@project/<platform>/server';
import { ProductRail } from '@project/island/organisms/product-rail';
import type { RelatedProductsProps } from './types';
export async function RelatedProducts({ productId }: RelatedProductsProps) {
const products = await getRelatedProducts(productId);
return <ProductRail products={products} linkAs={NavLink} />;
}
```
The rail renders each card's link with `linkAs`, the platform's `NavLink`, so a click is a client navigation and shows the pending hint while the product page loads ([rendering-patterns.md](rendering-patterns.md#loading-patterns)).
`.../product/[id]/organisms/product-reviews/ProductReviews.tsx`. The client pages through reviews, so this part hands its first page over through query hydration. `ReviewsList` is a client component that calls the part model.
```tsx
import { reviewKeys } from '@project/<platform>/features/catalog';
import { getProductReviews } from '@project/<platform>/server';
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { getQueryClient } from '../../../../../../configs';
import { ReviewsList } from './components/reviews-list';
import type { ProductReviewsProps } from './types';
export async function ProductReviews({ productId }: ProductReviewsProps) {
const queryClient = getQueryClient();
await queryClient.prefetchQuery({
queryKey: reviewKeys.list(productId, 1),
queryFn: () => getProductReviews(productId, 1),
});
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ReviewsList productId={productId} />
</HydrationBoundary>
);
}
```
`platforms/<platform>/src/features/catalog/models/product/use-product-reviews-part.ts`. Page 1 comes from the server; later pages load in the browser while the current page stays visible.
```ts
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { productsRepository, reviewKeys } from '../../repositories/products';
export function useProductReviewsPart(productId: string) {
const [page, setPage] = useState(1);
const reviews = useQuery({
queryKey: reviewKeys.list(productId, page),
queryFn: ({ signal }) => productsRepository.listReviews({ id: productId, page }, { signal }),
placeholderData: keepPreviousData,
});
return { reviews, page, setPage };
}
```
`apps/<app>/src/configs/react-query.ts`. The app's root client component passes `getQueryClient()` to `QueryClientProvider`. Older TanStack Query v5 releases use the `isServer` constant instead of `environmentManager.isServer()`. The error settings are explained in [error-handling.md](error-handling.md#reads).
```ts
import { handleError } from '@project/libs/error-handler';
import {
defaultShouldDehydrateQuery,
environmentManager,
QueryCache,
QueryClient,
} from '@tanstack/react-query';
function makeQueryClient(): QueryClient {
return new QueryClient({
queryCache: new QueryCache({
onError: (error, query) => {
if (query.state.data !== undefined) handleError(error, { where: 'refetch' });
},
}),
defaultOptions: {
queries: {
staleTime: 60_000,
retry: false,
networkMode: 'offlineFirst',
throwOnError: (_error, query) => query.state.data === undefined,
},
mutations: { networkMode: 'offlineFirst' },
dehydrate: {
shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending',
shouldRedactErrors: () => false,
},
},
});
}
let browserQueryClient: QueryClient | undefined;
export function getQueryClient(): QueryClient {
if (environmentManager.isServer()) return makeQueryClient();
browserQueryClient ??= makeQueryClient();
return browserQueryClient;
}
```

View File

@ -1,397 +0,0 @@
# Page rendering docs
Every page in a project has a rendering doc: one Markdown file that records, section by section, what the server HTML of each template holds and when each section's JavaScript loads. Search engines are certain to read only a page's server HTML, and Googlebot Smartphone crawls the mobile template, so a doc is written from Googlebot's point of view and checked against the real HTML. It is also where the team sees, before a change, which sections ship JavaScript. Default sections for common page types are in [page-type-maps.md](page-type-maps.md), the crawler rules a doc checks against are in [ui-rules.md](ui-rules.md#crawlers), and the way to choose where a section renders is in [rendering-patterns.md](rendering-patterns.md#choosing-where-a-part-loads).
Read the sections a task needs. To design a page: Where docs live, Vocabulary, Doc format, Index file, and Writing a doc. To write a missing doc: Where docs live, Vocabulary, Doc format, Index file, Producing a doc from code, and Checking the crawler view. To audit a page: Vocabulary, Doc format, Producing a doc from code, and Checking the crawler view. To change or review a page that has a doc: Vocabulary, Doc format, and Keeping docs current, then Checking the crawler view once the code is built. Doc format, Index file, and Example: home page hold `##` lines inside code blocks, so read each of them to the next heading that the Contents line names.
Contents: Where docs live · Vocabulary · Doc format · Index file · Writing a doc · Producing a doc from code · Checking the crawler view · Keeping docs current · Example: home page
## Where docs live
```
docs/pages/
├── README.md # the index file: one line per page and per layout
└── <app>/
├── layout-shop.md # the (shop) group's layout: header and footer, documented once
├── not-found.md # the app's not-found and error pages
├── home.md # /
├── product-id.md # /product/[id]
└── category-slug.md # /category/[...slug]
```
- `docs/pages/` sits at the monorepo root, beside `docs/decisions/`. Create it with the first doc.
- Write one doc per route, that is, per `page.tsx`. Name it from the route: drop route groups, join the segments with `-`, write a dynamic segment as its parameter name, and call `/` `home`. Brackets stay out of file names, so Markdown links to them work.
- A layout that renders UI, such as the header and footer, has its own doc: `layout.md` for the root layout, and `layout-<group>.md` for a route group's layout. A page doc links its layout doc and never repeats its rows. What crawlers get from a URL is its layout docs plus its page doc.
- A doc records decisions, never measurements: no sizes, timings, or dates, which change with every build. The PR plan records each key route's first-load JS and HTML size ([b2c-b2b.md](b2c-b2b.md#targets)).
- A rule for many pages is a decision ([decisions.md](decisions.md)), not a line in every doc.
## Vocabulary
- A section is a block of a page that a reader can name, such as the breadcrumb, the gallery, or the price. A part, in the rest of this skill, is a section with its own component; a part that loads on its own has its own `<Suspense>` and `PartBoundary`.
- An indexable page is a page whose robots value is `index`, or `index; noindex when <cause>`. Nothing above it streams: no `loading.tsx`, and no `<Suspense>` around `children` in a layout or in a component that a layout renders around them. A `noindex` or blocked page keeps its `loading.tsx` ([b2c-b2b.md](b2c-b2b.md#rendering)).
- An entity page is an indexable product, category, brand, seller, article, store branch, or campaign page: its URL names one record that can be missing or moved, so it answers a real 404 or 308 ([error-handling.md](error-handling.md#b2cb2b-server)).
- The first flush is the first bytes of the response: the shell, sent when everything outside a `<Suspense>` is ready; with `htmlLimitedBots`, it also waits for `generateMetadata`. On an indexable page, the shell holds everything outside the page's own `<Suspense>` parts, in place. A `<Suspense>` boundary that is complete by then is in place too, while the HTML of the shell, of the boundaries already in place, and its own stays within 12,800 bytes (React's `progressiveChunkSize`, which Next.js doesn't change), or when its own HTML is 500 bytes or less. Otherwise, its fallback is in place, and its content follows the footer, as for `streamed`.
- The First flush reads are the reads that the page's primary content needs. The page entry awaits them, `generateMetadata` reads the same caches when it needs data, and no Server Component outside a `<Suspense>` awaits any other read. A secondary section with a read of its own streams.
Each section gets three values. Use only these words, with these meanings. Each value has a code signal (Producing a doc from code).
**HTML**: what the response holds for the section, as a crawler reads it before any JavaScript runs. Crawlers get the same stream as browsers.
| Value | The server HTML holds |
|---|---|
| `first flush` | The real content, in the first flush, in document order. Every crawler reads it, whether or not it renders the page. |
| `streamed` | A skeleton in the first flush, and the real content later in the same response, in a hidden container at the end of `<body>`, such as `<div hidden id="S:n">` (`<table hidden>` for a part inside a table), until React's inline script moves it into place. It is the first content cut when the HTML passes Googlebot's 2 MB, and a slow part keeps the connection open, which uses up the site's crawl capacity. |
| `skeleton` | Only a same-size skeleton. The browser renders the real content, so Google sees it only after it renders the page, which is queued (seconds for most pages, hours for some) and not guaranteed, and then in the guest, first-visit state. |
| `none` | Nothing, such as a panel that mounts when it opens, a toast, or UI that a third-party script injects. |
**JS**: when the section's own client code loads. `next/link`, and the platform's `NavLink` that wraps it, count as `none`, because every page ships them.
| Value | The section's client code |
|---|---|
| `none` | None. The section is a Server Component, and nothing hydrates. |
| `hydrate` | In the route's first-load JavaScript, and it hydrates with the page. Both templates' client components ship to every device, so a `hydrate` row costs the other template too ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| `lazy` | Its own chunk, fetched when the component first renders: `next/dynamic` in a client component. Only the device that renders it downloads it. |
| `visible` | Its own chunk, fetched when the section comes near the viewport: a `next/dynamic` component inside `LoadOnVisible`. |
| `interaction` | Its own chunk, fetched on intent and rendered on click: a facade, or `await import()` in an event handler. |
**Index**: what search engines need from the section. It limits the HTML value.
| Value | The section holds | Allowed HTML |
|---|---|---|
| `primary` | What the page is about, which crawlers must read without rendering: the H1; the main entity's name, price, availability, description, specs, and rating summary; the breadcrumb; the LCP image; and the links that are the only path to other pages, such as pagination and the category menu. The JSON-LD is primary too, and lives in its field | `first flush`, in both templates |
| `secondary` | Content that search engines should read but that the page doesn't depend on: related products, reviews, rails, brand strips, and blog teasers | `first flush` or `streamed`, in both templates |
| `no` | Content that search engines don't need: viewer-dependent UI, countdown digits, controls, and chat | Any value; it may differ between templates |
The Data column says where a section's data comes from: a server cache call (`getProduct(id)`), `query` for a browser query, `viewer` for the auth store and the viewer's queries, `clock` for the shared clock, `config` for constants and i18n text, or `—` for none.
When a developer calls a section "static", it means HTML `first flush` with JS `none`: server HTML that ships no JavaScript. It never means static rendering at build time, which these apps never use, because every page renders fresh per request ([rendering-patterns.md](rendering-patterns.md#rendering-patterns)). When a developer calls a section "dynamic", it means a section whose JS isn't `none`, never Next.js dynamic rendering, which every page uses. Docs write the values, never "static" or "dynamic". For example, "the home page is all static, and the discount timer has JS" becomes: most home sections are `first flush` and `none`; the timer's end time is `first flush`, inside its section; and its digits are a `↳ Countdown digits` row with `skeleton`, `hydrate`, and `no`.
Common combinations:
- `first flush` + `hydrate`: an interactive leaf rendered on the server, such as add to cart or a slider.
- `skeleton` + `hydrate`: viewer-dependent or time-dependent UI.
- `skeleton` + `lazy`: heavy UI that renders at once, in the browser only.
- `skeleton` + `visible`: a browser part below the fold.
- `first flush` + `interaction`: a facade whose widget loads on click.
## Doc format
Copy this into `docs/pages/<app>/<page>.md`. Keep a doc under about 40 lines.
```markdown
# <Page name>
`<route>` · `apps/<app>/src/app/<path>/page.tsx` · Type: <page type> · Layout: [<layout doc>](<layout doc>)
| Field | Value |
|---|---|
| Robots | `index`, `index; noindex when <cause>`, `noindex` (<where it's set>), or `blocked` (<the robots.ts rule>) |
| Status | `200`; `404` when <cause>; `308` when <cause> |
| loading.tsx | `none` (indexable page), or `<path>/loading.tsx` |
| First flush | <the First flush reads: the cache reads that the primary content needs>, or `none` |
| Canonical | <URL pattern>; drops <parameters> |
| H1 | <where its text comes from> |
| JSON-LD | <builder>: <node types>, or `none` |
| Scripts | <third-party scripts and their next/script strategy>, or `none` |
## Sections
In the mobile template's document order.
| Section | Data | HTML | JS | Index | Notes |
|---|---|---|---|---|---|
| <section> | <data> | <value> | <value> | <value> | <template differences, trigger, link targets> |
## Notes
- <what the tables can't say: accepted trade-offs, developer overrides, debt>
```
How to fill it:
- Header line: the route as users see it, the `page.tsx` path, the page type from [page-type-maps.md](page-type-maps.md), and the layout doc around the page.
- Robots: `index` for an indexable page; `index; noindex when <cause>` for one that turns `noindex` in one case, such as a category with no products, with where it's set; `noindex` and where it's set, such as the `(account)` layout's `metadata`; or `blocked` and its `robots.ts` rule. A blocked page sets no robots tag, because Google never fetches it to read one.
- Status: every status the URL answers, with its cause. An entity page lists its 404, and its 308 when its record can move or be replaced. A page with a `loading.tsx` answers 200, even when its data is missing.
- loading.tsx: `none` on every indexable page; the file that wraps a `noindex` or blocked page.
- First flush: the First flush reads (Vocabulary), which the page entry awaits. The layout's reads are in the layout doc. Write `none` when the page reads nothing before its first byte.
- Canonical: the pattern that `generateMetadata` gives `alternates.canonical`, and the parameters it drops, such as variant, sort, and tracking parameters.
- H1: where its text comes from. Each template has one H1, with the same text.
- JSON-LD: the builder from the platform's `app/json-ld/`, or the `buildGraph` call, and its node types; `none` on a `noindex` or blocked page. The page entry renders it before the template.
- Scripts: each `next/script` from `packages/integrations` that renders no section, such as analytics, with its strategy. A third-party widget with UI, such as chat, is a section.
- Sections: one row per section the page renders, in the mobile template's document order. The layout's sections are in the layout doc.
- Name each row after its component, so a search finds the code.
- A piece of a section that renders differently from the rest of it gets its own row, starting with `↳`.
- A row that only one template has names that template, `(desktop)` or `(mobile)`, and is Index `no`.
- Notes: how the templates differ (`mobile: tabs, every panel in the DOM`), what triggers a deferred section, where its links go, and `override:` with the reason when the developer asked for a placement that breaks a default.
- Notes: only what the tables can't say. Leave the heading out when there is nothing to say.
- A layout doc has the title `# Layout: <group>`, then one line: `` `<layout.tsx path>` · wraps every page in `<route group>` · its reads, <cache reads>, are in every page's first flush; a failed read answers 500 on every page under it ``. Then come the Sections table and a `Scripts:` line. It has no Field table, and the ready-for-review checks apply to its rows.
A doc is ready for review when:
- every `primary` row is `first flush` in both templates;
- every `secondary` row is `first flush` or `streamed` in both templates;
- the JSON-LD field's builder takes only config or the First flush reads, and nothing outside a `<Suspense>` awaits a read beyond the First flush reads;
- no `skeleton` or `none` row holds text or links that search engines need;
- every row that one template lacks is Index `no`;
- an indexable page has loading.tsx `none`, and an entity page lists its 404, and its 308 when its record can move or be replaced.
## Index file
`docs/pages/README.md` lists every doc, one line each, grouped by app: the route, the doc, the robots value, the JSON-LD nodes, and the browser-only sections, which are the rows whose HTML is `skeleton` or `none`. A layout's line names the layout and lists only its browser-only sections. Read the index file before a task that touches several pages, and open only the docs the task needs.
```markdown
# Page rendering docs
One line per route: route · doc · robots · JSON-LD · browser-only sections.
## shop
- `(shop)` layout · [layout-shop.md](shop/layout-shop.md) · — · — · browser: user menu, cart count, search suggestions
- `/` · [home.md](shop/home.md) · index · OnlineStore, WebSite · browser: countdown digits, recommended for you
- `/product/[id]` · [product-id.md](shop/product-id.md) · index · Product or ProductGroup, BreadcrumbList · browser: countdown digits, membership offer, price history, zoom viewer
- `/search` · [search.md](shop/search.md) · blocked · none · browser: none
```
## Writing a doc
Write a new page's doc in `docs/pages/<app>/` before the code, and link it from the plan. It is the plan's record of where each section renders and when its code loads.
1. Start from the page type's map in [page-type-maps.md](page-type-maps.md). Remove the sections the design doesn't have, and add the ones it has.
2. Give each section its Index value first, from what search engines need. Then pick its HTML and JS values with [rendering-patterns.md](rendering-patterns.md#choosing-where-a-part-loads). The Index value limits the HTML value.
3. Decide whether the page is indexable. An indexable page has no `loading.tsx` above it, and an entity page among them answers a real 404, and a 308 when its record can move ([error-handling.md](error-handling.md#b2cb2b-server)); a `noindex` or blocked page keeps its `loading.tsx`. Then fill the other fields.
4. Run the ready-for-review checks under Doc format, and change the design where one fails.
5. Add the page's line to `docs/pages/README.md`.
6. After the code is built, run Checking the crawler view. Where the doc and the HTML disagree, fix the code or the doc.
## Producing a doc from code
To write a missing doc, or to audit a page, read the code and predict each row, then prove the rows with Checking the crawler view. Where the code and the HTML disagree, the HTML wins, with one exception: a section that the page's own code wraps in `<Suspense>` is `streamed`, even when a response shows it in place, because a part whose read finishes before the first flush is written in place on that request only.
1. List the files that shape the route: its `page.tsx`, and every `layout.tsx`, `loading.tsx`, `error.tsx`, and `not-found.tsx` from its folder up to `app/`. A `loading.tsx` in this list wraps the page. So does a `<Suspense>` around `children` in a layout, or in a component that a layout renders around `children`, such as the `AppShell` or a provider.
```bash
d='apps/<app>/src/app/(shop)/product/[id]'
while :; do ls "$d" | grep -E '^(page|layout|loading|error|not-found)\.tsx$' | sed "s|^|$d/|"; case "$d" in src/app|*/src/app|.|/) break;; esac; d=$(dirname "$d"); done
```
2. Read `page.tsx`:
- what the page entry awaits for its primary rows, and what `generateMetadata` awaits, give the First flush field; another read that the page entry awaits is a defect (below);
- where it calls `notFound()` and `permanentRedirect()`, and whether something from step 1 wraps it, give the Status and loading.tsx fields;
- the `metadata` or `generateMetadata` of the page and its layouts, and `robots.ts`, give the Robots and Canonical fields;
- the `<JsonLd>` element and its position give the JSON-LD field.
3. Walk each template's JSX in order. Each top-level organism is a row. Read each organism's files down to its leaves, and check each island or platform component it renders for `'use client'`: the leaves hold most of the signals in the table below. `grep -rlE "^['\"]use client" <organism folder>` lists the organism's own client files.
4. Record each finding below in the PR, or in the doc's Notes as debt.
| In the code | HTML | JS |
|---|---|---|
| A Server Component rendered from reads the page entry awaits, outside every `<Suspense>`, on an indexable page | `first flush` | `none` |
| On an indexable page, an async Server Component outside every `<Suspense>` that awaits a read beyond the First flush reads | `first flush`, which waits for that read | `none` |
| An async Server Component inside `<Suspense>`; or every row of a page under a `loading.tsx` once the shell's HTML and the page's pass 12,800 bytes | `streamed` | `none` |
| A `'use client'` component that a Server Component renders, with server props or hydrated query data | the value of the section around it | `hydrate` |
| `HydrationBoundary` with an awaited prefetch inside `<Suspense>`, `useSuspenseQuery` on an un-awaited prefetch, or a client component that reads an un-awaited server promise with `use()` inside `<Suspense>` | `streamed` | `hydrate` |
| Output decided by the auth store's `status`, by a `useQuery` with no server prefetch, or by `useClock` | `skeleton` | `hydrate` |
| Output rendered only after a mounted flag, a fetch in `useEffect`, or a `typeof window` check | `skeleton`, or `none` when it renders nothing until then | `hydrate` |
| `next/dynamic` with `ssr: false` | `skeleton` | `lazy` |
| `next/dynamic` without `ssr: false`, rendered at once | the value of the section around it | `lazy` |
| `LoadOnVisible` around a `next/dynamic` component | `skeleton` | `visible` |
| A facade that imports its widget on intent or click | `first flush`, the facade | `interaction` |
| A panel rendered only when open (`{isOpen && <Panel />}`), or content fetched on click | `none` | the trigger's value |
| `<details>`, or tabs and accordions that render every panel and hide the closed ones (island's `TabsPanel` with `forceMount`) | the value of the section around it | the toggle's value |
| `next/script` from `packages/integrations` | the Scripts field | the Scripts field |
Each finding below is a defect. Fix it, or record it as debt.
- An indexable page with a `loading.tsx` above it, or a `<Suspense>` around `children` in a layout or in a component a layout renders around them: an entity page answers 200 for a missing entity, at any size, and once the HTML passes React's 12,800-byte limit, the page's content follows the footer in a hidden `<div>`.
- On an indexable page, the page entry or a Server Component outside every `<Suspense>` that awaits a read beyond the First flush reads: the status line and the first byte wait for that read. Move it into a part inside `<Suspense>` and `PartBoundary`.
- JSON-LD in a layout, a template, a part inside `<Suspense>`, a client component, or `next/script`.
- A `primary` row that isn't `first flush`: inside a `<Suspense>` in the page's own code, in a `useQuery` part, behind `ssr: false`, inside `LoadOnVisible`, or behind a click. A `secondary` row that is `skeleton` or `none`.
- Content that search engines need kept out of the server HTML by a mounted flag, a fetch in `useEffect`, or a `typeof window` check: render it on the server, or use a technique from [rendering-patterns.md](rendering-patterns.md#choosing-where-a-part-loads).
- A tab, accordion, drawer, or slider that mounts a `primary` or `secondary` panel, or its links, only when open, or fetches them on click.
- Navigation through `onClick` with `router.push`, a `<button>`, or a clickable `<div>`; menu links fetched on hover or tap; page state, or an indexable filter's state, in a `#fragment`.
- A `primary` or `secondary` section, heading, link, or image that only one template has, or a different H1 in each template.
- A heavy client component that only one template renders, imported statically: every device downloads it. Load it through `next/dynamic` in a client component.
- `LoadOnVisible` around a statically imported client component: only its render waits, and its code is in the first-load JavaScript ([rendering-patterns.md](rendering-patterns.md#loading-patterns)).
- `isBot`, or a list of bots, in a rendering decision.
- `Date.now()` or `new Date()` in a client component's render; date formatting in a client component whose output the server renders; `suppressHydrationWarning` on time text; a `setInterval` per component.
- Robots tags, the canonical, or the title set or changed by client code.
- A locale or a currency on an indexable page taken from a cookie, `Accept-Language`, or the IP.
- Products reachable only through search or "Load more".
- HTML or first-load JS over its target ([b2c-b2b.md](b2c-b2b.md#targets)).
## Checking the crawler view
Check a production build, locally or on staging: build with the app's `build` target and run its `start` target (`nx show project <app>` lists them). The dev server's HTML differs from production. Run the checks for both templates, on the page of this type with the most content, in a new, empty folder.
1. Fetch the page as both Googlebots. Without `--compressed`, curl gets the uncompressed HTML, which is what Googlebot's 2 MB limit counts. The two byte counts together are the template's HTML size: check it against the HTML target ([b2c-b2b.md](b2c-b2b.md#targets)).
```bash
BASE='http://localhost:3000'
URL="$BASE/product/123"
STAGING_URL='https://<staging host>/product/123'
MOBILE='Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.122 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
DESKTOP='Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Chrome/141.0.7390.122 Safari/537.36'
curl -s -A "$MOBILE" -o mobile.html -w 'mobile: %{http_code}, %{size_header} + %{size_download} bytes\n' "$URL"
curl -s -A "$DESKTOP" -o desktop.html -w 'desktop: %{http_code}, %{size_header} + %{size_download} bytes\n' "$URL"
```
2. Split each response into what the first flush holds and what streams, with the scripts removed. `S` matches every hidden container that React streams into. The `.txt` files hold each part's text with React's `<!-- -->` separators removed and its HTML escapes decoded, so a search for a value the page shows matches.
```bash
S='<(?:div hidden |table hidden(?: |><(?:tbody|tr|colgroup) )|svg aria-hidden="true" style="display:none" |math aria-hidden="true" style="display:none" )id="S:'
D='s/<!-- -->//g; s/&#x27;/\x27/g; s/&quot;/"/g; s/&lt;/</g; s/&gt;/>/g; s/&amp;/&/g'
for t in mobile desktop; do
perl -0pe 's/<script\b.*?<\/script>//gs; s/'"$S"'.*//s' $t.html > $t.first-flush.html
perl -0ne 'print $1 if /('"$S"'.*)/s' $t.html | perl -0pe 's/<script\b.*?<\/script>//gs' > $t.streamed.html
perl -0ne 'print $1 if /<body\b[^>]*>(.*)/s' $t.first-flush.html | perl -pe "$D" > $t.first-flush.txt
perl -pe "$D" $t.streamed.html > $t.streamed.txt
done
```
3. Check the rows. Every `primary` row's text is in `*.first-flush.txt` of both templates, and every `secondary` row's text in `*.first-flush.txt` or `*.streamed.txt`. Search for one value that the page shows, such as `grep -c '<product name>' mobile.first-flush.txt desktop.first-flush.txt`. Each file is one line, so each count is 0 or 1.
4. Head, H1, and JSON-LD. Both templates have the same title, description, canonical, and robots tags, one H1 with the same text, and the same JSON-LD element. The diff proves only that the templates match, and the H1 count proves that each has one. The first offset that the last command prints must be the JSON-LD element, so it is in the first flush.
```bash
for t in mobile desktop; do
perl -0ne 'print "$1\n" if /<head>(.*?)<\/head>/s' $t.html | grep -o '<title>[^<]*</title>\|<meta name="description"[^>]*>\|<link rel="canonical"[^>]*>\|<meta name="robots"[^>]*>' > $t.head
perl -0ne 'print "$1\n" while /<h1\b[^>]*>(.*?)<\/h1>/gs' $t.first-flush.html | sed 's/<[^>]*>//g' >> $t.head
perl -0ne 'print "$1\n" while /<script type="application\/ld\+json">(.*?)<\/script>/gs' $t.html >> $t.head
echo "$t: $(grep -o '<h1\b' $t.first-flush.html | wc -l) H1" # 1 each
done
diff mobile.head desktop.head && cat mobile.head
grep -boP '<script type="application/ld\+json"|'"$S" mobile.html | head -2
```
Then run the page through the Rich Results Test as Googlebot Smartphone: in URL mode on a staging host that the internet can reach, or in code mode with `mobile.html` for a local build. For the home page, use the Schema Markup Validator ([lib-json-ld.md](lib-json-ld.md#testing-and-monitoring)).
5. Links and images. Both templates have the same `<a href>` links, image URLs, and alt texts, in the first flush or streamed; step 3 proves which ones are in the first flush. Each line that `diff` prints is a link or an image that only one template has, which only an Index `no` row may have. The `sed` drops `next/image`'s width and quality, which change with each template's image size.
```bash
for t in mobile desktop; do
cat $t.first-flush.html $t.streamed.html | grep -o '<a [^>]*href="[^"#][^"]*"' | grep -o 'href="[^"]*"' | sort -u > $t.links
cat $t.first-flush.html $t.streamed.html | grep -o '<img [^>]*>' | grep -o ' \(src\|alt\)="[^"]*"' | sed 's/&amp;w=[0-9]*&amp;q=[0-9]*//' | sort -u >> $t.links
done
diff mobile.links desktop.links
```
6. Status, `robots.txt`, and `Vary`. On an entity page, a missing entity answers 404, and a replaced one 308 with its target. No `Disallow` line matches an indexable page, its variant URLs, or `/_next/static/`; a blocked page matches its own rule, such as `Disallow: /search`. On staging, behind the reverse proxy or the CDN and never on a local start, every HTML response's `Vary` includes `User-Agent`.
```bash
curl -s -o /dev/null -A "$MOBILE" -w '%{http_code} %{redirect_url}\n' "$BASE/product/does-not-exist" # 404
curl -s -o /dev/null -A "$MOBILE" -w '%{http_code} %{redirect_url}\n' "$BASE/product/<replaced-id>" # 308 <replacement URL>
curl -s "$BASE/robots.txt" | grep -i '^disallow'
curl -s -o /dev/null -D - -A "$MOBILE" "$STAGING_URL" | grep -i '^vary:' # includes User-Agent
```
7. States. For each case that the doc's Status, Robots, and Canonical fields name, set `URL` to one URL of that case, and run steps 1 to 4 again in a new, empty folder. Then check: a variant URL (200; its price in the first flush; a canonical without the variant parameters), an out-of-stock product (200; its stock text in the first flush; `OutOfStock` in the JSON-LD), `?page=2` of a listing (200; its own canonical; `<a href>` links to the previous and next pages), and a page past the last or an empty combination of indexable filters (404 for both user agents in step 1; skip steps 2 to 4).
8. In the browser. Open the page in Chrome, with the Googlebot Smartphone user agent from DevTools' Network conditions. The console shows no React error. Production reports a text mismatch, such as a clock read during render, as `Minified React error #418`. It reports a missing `getServerSnapshot` inside a `<Suspense>` as `#419`, and the server HTML then holds only that boundary's fallback. Outside every `<Suspense>`, as for a section in an indexable page's first flush, a missing `getServerSnapshot` fails the whole response instead: a 500 with `noindex` and an empty `<body>`, which step 1's status shows, and no React error in the console. Then turn JavaScript off and reload. What still shows is the `first flush` content; streamed sections keep their skeletons, although their HTML is in the response.
9. JavaScript per route. `next build` stopped printing first-load JS in Next.js 16. Next.js 16.4 writes each route's first-load chunks to `.next/diagnostics/route-bundle-stats.json`, an undocumented file, so check that it still exists after an upgrade. Run this where the build's `.next/` folder is. Route-specific JS is the first-load JS minus the chunks that every route shares.
```bash
node -e '
const fs = require("fs"), zlib = require("zlib");
const stats = require("./.next/diagnostics/route-bundle-stats.json");
const gz = (f) => zlib.gzipSync(fs.readFileSync(f)).length;
const shared = stats.map((r) => r.firstLoadChunkPaths).reduce((a, b) => a.filter((f) => b.includes(f)));
for (const { route, firstLoadChunkPaths: c } of stats) console.log(route.padEnd(40), (c.reduce((s, f) => s + gz(f), 0) / 1024).toFixed(1), "KB first-load,", (c.filter((f) => !shared.includes(f)).reduce((s, f) => s + gz(f), 0) / 1024).toFixed(1), "KB route-specific (gzip)");'
```
The file leaves out the chunk of a `next/dynamic` component that a template renders at once, which that template's HTML preloads. So also measure each template from step 1's HTML, and check the larger number against the target. In the check folder, list each template's chunks; the pattern skips the `noModule` polyfills and accepts the `?dpl=` that `NEXT_DEPLOYMENT_ID` adds:
```bash
for t in mobile desktop; do perl -0ne 'print ".next/$1\n" while /<(?:script src|link rel="preload"[^>]*href)="\/_next\/(static\/chunks\/[^"?]+\.js)(?:\?[^"]*)?"(?![^>]*noModule)/g' $t.html | sort -u > $t.chunks; done
```
Then, where the build's `.next/` folder is:
```bash
node -e 'const fs = require("fs"), zlib = require("zlib"); for (const list of process.argv.slice(1)) console.log(list, (fs.readFileSync(list, "utf8").trim().split("\n").reduce((s, f) => s + zlib.gzipSync(fs.readFileSync(f)).length, 0) / 1024).toFixed(1), "KB gzip")' <check folder>/mobile.chunks <check folder>/desktop.chunks
```
`next analyze` shows what a route's client JavaScript holds and why each module is there, and `next analyze --output` writes the same data to `.next/diagnostics/analyze` without a server. Its route totals also count the `noModule` polyfills, which modern browsers skip, and use their own compressed size, so compare only the numbers above with the target.
After a release, Search Console shows what Google got. URL Inspection's live test gives the rendered HTML, a screenshot, and the console messages, as Googlebot Smartphone. In the Page indexing report, a rise in "Soft 404" or "Excluded by 'noindex' tag" for an indexable page type means a template lost its content or answers the wrong status. Crawl stats give the response time and the status per response code.
## Keeping docs current
- Update the doc in the same PR as any change to the page's sections, their data reads, their HTML, JS, or Index values, or the page's robots, status, canonical, JSON-LD, or scripts. A change inside a section that keeps its data read and its HTML, JS, and Index values needs no doc change.
- Update the layout doc when the header or footer changes, and the index line when the robots value, the JSON-LD, or the browser-only sections change.
- A route without a doc gets one in the first PR that changes it. Produce it from code, in its own commit.
- Read a page's doc before you change the page. It says where each section renders, without opening every file.
- The reviewer reads the doc's diff first, runs the ready-for-review checks, and checks that the code diff matches the doc. A rendering change without its doc change blocks the merge ([definition-of-done.md](definition-of-done.md#review)).
- SEO and QA read the docs and the index file for the crawler view of every page.
## Example: home page
A Digikala-like shop. The header and footer live in `(shop)/layout.tsx`, so `layout-shop.md` documents them once, and the home doc links it.
`docs/pages/shop/layout-shop.md`:
```markdown
# Layout: shop
`apps/shop/src/app/(shop)/layout.tsx` · wraps every page in `(shop)` · its reads, `getMenu()`, are in every page's first flush; a failed read answers 500 on every page under it
| Section | Data | HTML | JS | Index | Notes |
|---|---|---|---|---|---|
| Logo | config | first flush | none | primary | `<a href="/">`; its alt text is the store's name |
| SearchBox | — | first flush | hydrate | no | a GET form to `/search`, so it works before hydration |
| ↳ SearchSuggestions | query | none | interaction | no | the code loads on focus; suggestions load from the second typed character, debounced 300 ms |
| CategoryMenu | `getMenu()` | first flush | hydrate | primary | desktop: a mega menu that opens on hover; mobile: a drawer; both keep every category's `<a href>` in the DOM while closed |
| UserMenu | viewer | skeleton | hydrate | no | guest: a login link; member: the account menu |
| CartCount | viewer | skeleton | hydrate | no | the badge keeps its box while the viewer is unknown |
| BottomNavigation (mobile) | config | first flush | none | no | home, categories, cart, and account |
| FooterLinks | `getMenu()`, config | first flush | none | primary | top categories, store branches, policies, about, and contact |
| NewsletterForm | — | first flush | hydrate | no | |
| ChatButton | — | first flush | interaction | no | the chat integration's facade; the widget loads on click |
Scripts: analytics, `next/script` with `lazyOnload`.
```
`docs/pages/shop/home.md`:
```markdown
# Home
`/` · `apps/shop/src/app/(shop)/page.tsx` · Type: home · Layout: [layout-shop.md](layout-shop.md)
| Field | Value |
|---|---|
| Robots | `index` |
| Status | `200` |
| loading.tsx | `none`: links to `/` are `NavLink`s |
| First flush | `getHomePage()`, which the page entry awaits; the metadata is fixed, in the `metadata` export |
| Canonical | `/`; drops tracking parameters |
| H1 | `home:title` from i18n, in the hero section |
| JSON-LD | `buildOrganization(SEO_ORGANIZATION)` and `buildWebSite(SEO_WEBSITE)` from `configs/seo.ts`: `OnlineStore`, `WebSite` |
| Scripts | none beyond the layout's |
## Sections
In the mobile template's document order.
| Section | Data | HTML | JS | Index | Notes |
|---|---|---|---|---|---|
| HeroBanners, with the H1 | `getHomePage()` | first flush | hydrate | primary | every slide's `<a href>` and `<img>` in the DOM; the first image eager with high fetch priority, the others lazy; the slider leaf only moves the slides |
| CategoryTiles | `getHomePage()` | first flush | none | primary | an `<a href>` per top category; mobile: one scrolling row; desktop: a grid |
| OffersRail | `getHomePage()` | first flush | none | secondary | 20 cards, each an `<a href>` with a name, image, price, struck-through price, and discount; the header says when the offers end, in a `<time>` formatted on the server |
| ↳ Countdown digits | clock | skeleton | hydrate | no | one `Countdown` in the rail's header, not one per card; at zero its ended label replaces the digits, and nothing refreshes |
| CampaignBanners | `getHomePage()` | first flush | none | primary | an `<a href>` to each campaign's permanent URL, the only links to campaign pages |
| BestsellerRails | `getBestsellers(categoryId)` | streamed | none | secondary | three rails, each in its own `<Suspense>` and `PartBoundary`; category pagination reaches the same products |
| RecommendedForYou | viewer | skeleton | visible | no | members: personal picks; guests, and Google: popular products |
| BrandStrip | `getHomePage()` | first flush | none | secondary | an `<a href>` per brand page |
| BlogTeasers | `getHomePage()` | first flush | none | primary | an `<a href>` per latest article, the only links into the blog from outside it |
## Notes
- Desktop shows the offers rail beside the hero, and mobile shows it below the category tiles. Both templates hold the same sections.
- The rail's offers end together, so the rail has one countdown. On each product page, the same `discountEndsAt` is the offer's sale end in the JSON-LD and the product countdown's `endsAt`.
```
How the example meets the rules:
- The header and footer are documented once, and their primary rows are in every page's first flush.
- The home page is indexable, so nothing above it streams: its primary content and JSON-LD are in the shell, in place, whatever the page's size ([b2c-b2b.md](b2c-b2b.md#rendering)). A click on a link to `/`, a `NavLink`, shows its pending hint until the page arrives.
- The discount timer's end time is server HTML. Only its digits are a browser leaf, and they are never indexable content ([rendering-patterns.md](rendering-patterns.md#time-dependent-ui)).

View File

@ -1,249 +0,0 @@
# Page type maps
The default sections of common e-commerce page types. A page's rendering doc starts from its type's map ([page-rendering.md](page-rendering.md#writing-a-doc)): copy the rows the design has, add the Notes column, and add or remove sections. The doc, not this file, records what a page does. The values are defined in [page-rendering.md](page-rendering.md#vocabulary), and the rules behind them are in [ui-rules.md](ui-rules.md#crawlers).
Contents: Layout: header and footer · Home · Category and brand listing · Search results · Product · Campaign and offers · Blog article · Static and policy pages · Store branch · Seller · Cart and checkout · Account · Login · Compare · Not-found and error
Each section starts with one line: the route, its robots value, the statuses it answers, its JSON-LD, and its First flush reads, the reads its primary content needs. Indexable pages have no `loading.tsx` above them, and every link to them is the platform's `NavLink`. Entity pages among them (product, category, brand, seller, article, store branch, campaign) answer a real 404, and a 308 when their record can move ([error-handling.md](error-handling.md#b2cb2b-server)). `noindex` and blocked pages keep their `loading.tsx` ([b2c-b2b.md](b2c-b2b.md#rendering)).
## Layout: header and footer
`(shop)/layout.tsx` · one doc, `layout-shop.md`, which every page doc under it links · its awaited reads are in every page's first flush and hold every page's first byte; a failed read answers 500 on every page under it
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Logo, linked to `/` | config | first flush | none | primary |
| Search box | — | first flush | hydrate | no |
| ↳ Search suggestions | query | none | interaction | no |
| Category menu: mega menu (desktop), drawer (mobile) | `getMenu()` | first flush | hydrate | primary |
| User menu or login link | viewer | skeleton | hydrate | no |
| Cart count | viewer | skeleton | hydrate | no |
| Bottom navigation (mobile) | config | first flush | none | no |
| Footer links: categories, branches, policies, about, contact | `getMenu()`, config | first flush | none | primary |
| Newsletter form | — | first flush | hydrate | no |
| Chat button | — | first flush | interaction | no |
- The menu's category links are `<a href>` in the server HTML of both templates. Hover and tap only show them, and the drawer keeps them in the DOM while it's closed.
- The search box is a `GET` form to `/search`, so it works before hydration.
- Analytics goes on the Scripts line, with `next/script` and `afterInteractive` or `lazyOnload`.
- Keep the layout's reads few and fast: every page's first byte waits for them.
## Home
`/` · index · 200 · JSON-LD: `OnlineStore` and `WebSite` from `configs/seo.ts` · first flush: `getHomePage()`, which the page entry awaits; the metadata is fixed. The filled doc is in [page-rendering.md](page-rendering.md#example-home-page).
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| H1 and hero banners | `getHomePage()` | first flush | hydrate | primary |
| Top category tiles | `getHomePage()` | first flush | none | primary |
| Offers rail, with its end time | `getHomePage()` | first flush | none | secondary |
| ↳ Countdown digits | clock | skeleton | hydrate | no |
| Campaign banners | `getHomePage()` | first flush | none | primary |
| Bestseller rails | `getBestsellers(categoryId)` | streamed | none | secondary |
| Recommended for you | viewer | skeleton | visible | no |
| Brands | `getHomePage()` | first flush | none | secondary |
| Blog teasers | `getHomePage()` | first flush | none | primary |
- Top categories and bestsellers are `<a href>` in the server HTML: the home page passes the most link weight.
- Campaign banners link each campaign's permanent URL, and blog teasers link the latest articles: they are the only links to campaign pages and into the blog, so both are `primary`.
## Category and brand listing
`/category/[...slug]`, `/brand/[slug]` · index; `noindex` when it has no products while the menu links it · entity page: 404 for an unknown slug, a page past the last, or an empty, duplicate, or unknown combination of indexable filters; 308 for a moved category; 200 with the `no-results` empty state and Clear filters for an empty combination that includes a filter `robots.ts` blocks · JSON-LD: `BreadcrumbList` · first flush: `getCategory(slug)` and `getListing(slug, page, filters)`
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Breadcrumb | `getCategory(slug)` | first flush | none | primary |
| H1 and intro text | `getCategory(slug)` | first flush | none | primary |
| Subcategory links | `getCategory(slug)` | first flush | none | primary |
| Filters: sidebar (desktop), sheet (mobile) | `getListing(slug, page, filters)` | first flush | hydrate | secondary |
| Sort | — | first flush | hydrate | no |
| Product grid | `getListing(slug, page, filters)` | first flush | none | primary |
| ↳ Add to cart | — | first flush | hydrate | no |
| ↳ Wishlist state | viewer | skeleton | hydrate | no |
| Pagination | `getListing(slug, page, filters)` | first flush | none | primary |
| Load more (mobile) | query | first flush | hydrate | no |
| Category description | `getCategory(slug)` | first flush | none | secondary |
- Each card holds the product's name, image, price, and availability, and an `<a href>` to its page. Cap the page size, so the largest page stays within the HTML target.
- `filters` is the canonical filter string, a primitive, so the cache matches ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- Indexable filter links are `<a href>` in both templates, and the mobile sheet keeps them in the DOM while it's closed. Filter options show their product count and disable an option that would leave no products, so no link leads to an empty combination.
- "Load more" is an `<a href>` to the next page that JavaScript enhances, so the pagination links stay the crawl path.
- A category with no products is `noindex` while the menu links it, and answers 404 once it leaves the menu.
## Search results
`/search?q=` · blocked: `robots.ts` disallows `/search`, and the page sets no robots tag · 200 for every query, never 5xx; keeps its `loading.tsx` · JSON-LD: none · first flush: none; the results stream
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Query heading and result count | `getSearch(q, page)` | streamed | none | no |
| Filters and sort | `getSearch(q, page)` | streamed | hydrate | no |
| Results grid | `getSearch(q, page)` | streamed | none | no |
| Pagination | `getSearch(q, page)` | streamed | none | no |
- Search renders on the server for its users, not for crawlers. Category pagination reaches every product without it.
- No results: the `no-results` empty state, with 200.
## Product
`/product/[id]` · index · entity page: 404 when missing, 308 to its replacement; out of stock stays 200 · JSON-LD: `Product`, or `ProductGroup` with variants, and `BreadcrumbList` · first flush: `getProduct(id)`
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Breadcrumb | `getProduct(id)` | first flush | none | primary |
| Gallery: main image | `getProduct(id)` | first flush | none | primary |
| Gallery: other images and thumbnails | `getProduct(id)` | first flush | hydrate | secondary |
| Zoom viewer | — | none | interaction | no |
| H1, brand link, and rating summary | `getProduct(id)` | first flush | none | primary |
| Price, struck-through price, availability, and sale end time; on a marketplace, the buy box's seller, linked to its page | `getProduct(id)` | first flush | none | primary |
| ↳ Countdown digits | clock | skeleton | hydrate | no |
| Variant links | `getProduct(id)` | first flush | none | primary |
| Add to cart | — | first flush | hydrate | no |
| Membership offer | viewer | skeleton | hydrate | no |
| Description and specs | `getProduct(id)` | first flush | hydrate | primary |
| Shipping and returns summary | `getProduct(id)` | first flush | none | secondary |
| Related products | `getRelatedProducts(id)` | streamed | none | secondary |
| Reviews, first page | `getProductReviews(id, 1)` | streamed | hydrate | secondary |
| Price history | query | skeleton | visible | no |
| Product video | `getProduct(id)` | first flush | interaction | no |
- Variants: each variant has its own URL (`?color=green&size=s`). The server preselects its image, price, and availability from the URL. The canonical drops the variant parameters, and the `ProductGroup` markup stays the same.
- Out of stock: 200, with the stock text and a disabled add-to-cart in the first flush, and `OutOfStock` in the offer.
- Description and specs: on mobile, tabs or accordions with every panel in the DOM.
- The countdown's `endsAt` and the offer's `saleEnds` are the same `discountEndsAt` ([rendering-patterns.md](rendering-patterns.md#time-dependent-ui)).
- The video is a facade with its poster in the first flush; the player loads on click.
## Campaign and offers
`/campaign/[slug]` · index · entity page: 404 for an unknown slug or a page past the last; 308 when its slug changes; between seasons, the page stays 200 with its event text and its next dates · JSON-LD: `BreadcrumbList` · first flush: `getCampaign(slug)` and `getCampaignProducts(slug, page)`
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Breadcrumb | `getCampaign(slug)` | first flush | none | primary |
| H1 and event text | `getCampaign(slug)` | first flush | none | primary |
| Sale window: start and end time | `getCampaign(slug)` | first flush | none | secondary |
| ↳ Countdown digits | clock | skeleton | hydrate | no |
| Offer grid | `getCampaignProducts(slug, page)` | first flush | none | primary |
| Pagination | `getCampaignProducts(slug, page)` | first flush | none | primary |
| Category shortcuts | `getCampaign(slug)` | first flush | none | secondary |
- Use one permanent URL per recurring event, reused every year and linked from the home page. Never a new URL per season.
- The event text and the offers are the indexable content; the countdown never is.
- A standing offers page, such as `/offers`, uses the same map. It is indexable, so it has no `loading.tsx`, and a page past the last answers 404.
## Blog article
`/blog/[slug]` · index · entity page: 404 when missing, 308 when moved · JSON-LD: `BreadcrumbList`, and `BlogPosting` once the json-ld lib has a builder for it ([lib-json-ld.md](lib-json-ld.md#adding-a-type)) · first flush: `getArticle(slug)`
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Breadcrumb | `getArticle(slug)` | first flush | none | primary |
| H1, author, and date | `getArticle(slug)` | first flush | none | primary |
| Cover image | `getArticle(slug)` | first flush | none | primary |
| Body | `getArticle(slug)` | first flush | none | primary |
| Table of contents | `getArticle(slug)` | first flush | none | secondary |
| Products in the article | `getArticleProducts(slug)` | streamed | none | secondary |
| Related articles | `getRelatedArticles(slug)` | streamed | none | secondary |
| Share buttons | — | first flush | hydrate | no |
| Comments | query | skeleton | visible | no |
- The date is formatted on the server, inside `<time dateTime>`.
- Table-of-contents links are fragments within the page, and never change its content.
## Static and policy pages
`/about`, `/contact`, `/faq`, `/policies/returns`, `/policies/shipping` · index · 200 · JSON-LD: the returns page has `buildOrganization` with `returnPolicy`, the shipping page has it with `shipping`, and the rest have none · first flush: none, or the content read
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Breadcrumb | config | first flush | none | primary |
| H1 and body | config, or the content read | first flush | none | primary |
| FAQ answers | config | first flush | none | primary |
| Contact form | — | first flush | hydrate | no |
| Map | — | first flush | interaction | no |
- FAQ answers sit in `<details>`, every answer in the DOM, and need no JavaScript. No `FAQPage` markup ([lib-json-ld.md](lib-json-ld.md#what-the-markup-may-say)).
- The returns and shipping pages show the same facts as their JSON-LD, from `configs/seo.ts`.
- The map is a facade: a static image in the first flush, and the interactive map on click.
## Store branch
`/stores/[slug]` · index · entity page: 404 when closed for good, 308 when moved · JSON-LD: `Store` and `BreadcrumbList` · first flush: `getStore(slug)`
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Breadcrumb | `getStore(slug)` | first flush | none | primary |
| H1, address, and phone | `getStore(slug)` | first flush | none | primary |
| Opening hours | `getStore(slug)` | first flush | none | primary |
| ↳ Open-now badge | clock | skeleton | hydrate | no |
| Photos | `getStore(slug)` | first flush | hydrate | secondary |
| Map | — | first flush | interaction | no |
| Other branches in the city | `getStores(city)` | streamed | none | secondary |
- The hours table is formatted on the server and matches the JSON-LD's opening hours. The badge only adds whether the branch is open now, in the browser ([rendering-patterns.md](rendering-patterns.md#time-dependent-ui)).
- The phone number is a `tel:` link.
## Seller
`/seller/[slug]` · index · entity page: 404 when missing or for a page past the last, 308 when renamed · JSON-LD: `BreadcrumbList` · first flush: `getSeller(slug)` and `getSellerProducts(slug, page)`
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Breadcrumb | `getSeller(slug)` | first flush | none | primary |
| H1 and seller facts | `getSeller(slug)` | first flush | none | primary |
| Seller ratings | `getSellerRatings(slug)` | streamed | none | secondary |
| Product grid | `getSellerProducts(slug, page)` | first flush | none | primary |
| Pagination | `getSellerProducts(slug, page)` | first flush | none | primary |
| Follow seller | viewer | skeleton | hydrate | no |
- Product pages link their seller from the buy box with `<a href>`: that link is the seller pages' crawl path.
- No rating markup for the seller: ratings go on products only ([lib-json-ld.md](lib-json-ld.md#what-the-markup-may-say)).
## Cart and checkout
`/cart`, `/checkout/*` · `noindex` in their layout's `metadata`, never blocked in `robots.ts` · keeps its `loading.tsx` · JSON-LD: none · first flush: none; every section depends on the viewer, so the page renders in the browser
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Items, totals, and steps | viewer | skeleton | hydrate | no |
| Recommendations | query | skeleton | visible | no |
- Storebot-Google walks the product page, add-to-cart, the cart, and checkout to check prices and shipping. They work for an automated browser that keeps cookies, and bot protection lets verified Google crawlers through.
- Cart and checkout price on the server, and never trust a price that a page showed.
## Account
`/account/*` · `noindex` in the `(account)` layout's `metadata` · keeps its `loading.tsx` · JSON-LD: none · first flush: none; behind `AuthGuard`, rendered in the browser ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui))
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Every section | viewer | skeleton | hydrate | no |
## Login
`/auth/login` · `noindex` in its `metadata` · keeps the `(auth)` `loading.tsx` · JSON-LD: none · first flush: none
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| H1 and phone form | — | first flush | hydrate | no |
| OTP step | — | none | hydrate | no |
- The form is the same for every visitor, so the server renders it.
## Compare
`/compare?ids=` · blocked: `robots.ts` disallows `/compare`, because every set of ids is a new URL · keeps its `loading.tsx` · JSON-LD: none · first flush: none; the table streams
| Section | Data | HTML | JS | Index |
|---|---|---|---|---|
| Compare table | `getProducts(ids)` | streamed | none | no |
| Add and remove controls | — | streamed | hydrate | no |
## Not-found and error
One doc, `not-found.md`, covers the app's not-found and error pages: for each not-found and error case in the status table of [error-handling.md](error-handling.md#b2cb2b-server) (a missing entity, a listing page past the last, a failed read, `notFound()` or a failed read under a `loading.tsx`, and overload), its status and what the server HTML holds.
- They render no JSON-LD, and every one of them is `noindex`.
- Google needs only a non-200 page's status, and it may not render such a page at all. So nothing on it depends on JavaScript for crawlers. The server HTML of a real 404 has an empty `<body>`, and the not-found UI renders in the browser.
- No page answers 410: Google treats it like 404, and Next.js has no API for it.

View File

@ -1,410 +0,0 @@
# Project structure
`<placeholders>` are names you choose. `@project` stands for the workspace's npm scope. A product has one platform and one or more apps that share it: `<app>` names an app, `<platform>` the product's platform, and `<product>` the product.
Contents: Top level · App · Platform · Feature anatomy · Shared · island · Choosing where a component goes · libs, integrations, and tools packages · Env flow · Nx tags and boundaries · Exports and tree-shaking
## Top level
```
apps/ # deployable apps
platforms/ # each product's logic, one project per product, shared by its apps
packages/
├── island/ # design system (atomic design)
├── libs/ # framework-agnostic libraries, e.g. http and env
├── integrations/ # third-party integrations
└── tools/ # shared runtime tools
tools/ # workspace scripts for AI, Nx, and the repo, e.g. a doc validator or generate-splash-screens.ts
docs/
├── decisions/ # ADRs and DDRs, one file each, and their index, README.md (see decisions.md)
└── pages/ # one rendering doc per route, and their index, README.md (see page-rendering.md)
```
Three folders are named `tools`. Keep them apart:
- Root `tools/`: scripts that run in a terminal, in CI, or through Nx (generators, validators). App code never imports them. TypeScript scripts run with jiti.
- `packages/tools/`: shared runtime tools that apps and projects import.
- `packages/island/src/tools/`: design-system tools such as `cn`, `cvx`, `icon-sprite-plugin`, `font-copy-plugin`, and `icon-name-extraction`.
## App (Next.js)
```
apps/<app>/src/
├── bootstrap/
│ ├── bootstrap.client.ts # runs before client components render (SSR and browser)
│ ├── bootstrap.server.ts # runs once on the server before rendering
│ └── index.ts
├── i18n/
│ ├── i18n.ts
│ └── index.ts
├── instrumentation.ts # configures the error handler on the server; onRequestError reports
├── 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
│ ├── error.tsx # page-size EB-S for the group
│ └── auth/
│ └── login/
│ ├── page.tsx
│ ├── organisms/ # optional: organisms only this route uses
│ └── templates/ # optional: this route's mobile and desktop templates
├── styles/
│ ├── app.css # Tailwind entry; imports island.css
│ └── index.ts
├── configs/
│ ├── seo.ts # metadata defaults, ROOT_VIEWPORT, 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) and the iOS startup images
│ └── index.ts
├── constants/
│ ├── auth.ts # e.g. the OTP re-send timeout
│ └── index.ts
└── env/ # the only code that reads process.env (see lib-env.md)
├── env.client.ts # public variables: createClientEnv
├── env.server.ts # server variables: createServerEnv; import 'server-only'
├── index.ts # clientEnv
└── server.ts # serverEnv; import 'server-only'
```
- Pages are thin entrypoints. A page picks the mobile or the desktop template on the server, so no component branches on viewport size.
- A `loading.tsx` wraps every page below its folder, so none sits above an indexable page: it would move the page's content after the footer, and turn an entity page's 404 or 308 into a 200 ([b2c-b2b.md](b2c-b2b.md#rendering)). Only a `noindex` or blocked page has one: put it beside its page, or in a route group that holds only such pages, such as `(account)` or `(auth)`.
- `apps/<app>/public/` holds the committed manifest icons in `pwa/`, the iOS startup images in `pwa/splash/`, 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.
## Platform
```
platforms/<platform>/src/
├── app/
│ ├── app-shell/ # top-level provider shell shared by the mobile and desktop views
│ │ ├── AppShell.tsx
│ │ ├── types.ts
│ │ └── index.ts
│ ├── guards/ # e.g. AuthGuard for pages that need a logged-in user
│ │ └── <guard-name>/
│ │ ├── <guard-name>.ts or <GuardName>.tsx
│ │ └── index.ts
│ ├── error-boundaries/ # see error-handling.md
│ │ ├── part-boundary/ # PartBoundary: catchError around a part
│ │ ├── 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
│ │ ├── types.ts
│ │ ├── hooks/
│ │ │ └── use-<hook-name>.ts
│ │ ├── components/ # navigation UI, shaped like organisms, e.g. nav-link
│ │ └── index.ts
│ └── screens/ # UI that knows a domain and serves several routes or apps
│ ├── organisms/ # shared by routes with no common route level
│ ├── templates/
│ └── (auth)/ # mirrors the apps' route tree
│ ├── organisms/ # shared by routes under (auth)
│ ├── templates/
│ └── auth/
│ └── login/
│ ├── organisms/ # shared by the login route of several apps, or by routes under it
│ └── templates/
├── features/ # DDD, see Feature anatomy
├── stores/ # one store per feature or domain
├── shared/ # see Shared
├── index.ts
└── server.ts
```
`screens/` holds organisms and templates that know a domain and that several routes, or the same route in several apps, use. They can't go to island, because island is domain-free. They can't go to an app's route level, because one route level can't serve another route or another app.
- Its folders mirror the route tree. A component sits at the nearest route level that every route using it shares. Create a level's folder only when something lives in it.
- `organisms/` and `templates/` hold component modules shaped like island organisms.
- Its components know a domain: they call a model or an action, read a store, or take a `*Payload`. The logic itself stays in the feature's models and actions, so the components stay presentational.
- 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
```
features/<feature>/
├── entities/ # back-end data model: types, enums, unions
│ └── <entity-name>/
│ ├── types.ts
│ └── index.ts
├── repositories/ # request + return data; no client-side dependencies
│ └── <repository-name>/
│ ├── <repository-name>.ts
│ ├── types.ts # e.g. LoginArgs, LoginDto, LoginResponseDto, LoginPayload
│ ├── mappers.ts # *Args → *Dto (outgoing), *ResponseDto → *Payload (incoming)
│ ├── constants.ts # endpoints and query keys
│ └── index.ts
├── caches/ # server-only React cache() reads
│ ├── <cache-name>.ts
│ ├── types.ts
│ ├── constants.ts
│ └── server.ts # the module's entry; no index.ts
├── actions/
│ └── <action-name>/
│ ├── actions.ts # the operation from start to end; emits its event
│ └── index.ts
├── models/ # logic per page and per part, as hooks
│ ├── login/ # a page with one model
│ │ ├── use-login-page.ts
│ │ ├── types.ts
│ │ ├── constants.ts
│ │ └── index.ts
│ └── shipment/ # a page model plus one model per part
│ ├── use-shipment-page.ts
│ ├── use-shipment-address-part.ts
│ ├── use-shipment-legal-part.ts
│ ├── use-shipment-bill-part.ts
│ └── index.ts
├── http.ts # the feature's HTTP client: http.extend(...); used only by its repositories
├── types.ts
├── constants.ts
└── index.ts # never exports the http.ts client
```
Rules inside a feature:
- Layers import only from earlier layers: entities → repositories → actions → models → UI.
- Repositories import only entities, libs, the feature's `http.ts`, and their own files. Actions may also use stores and browser libs such as `storage`, `cookie`, and the event emitter. Models may also use actions, stores, and validations.
- Caches sit beside that chain, on the server: they import only entities, repositories, and their own files, and only server code imports them (server page loaders in `models/`, pages, `generateMetadata`, and server components). Details: [b2c-b2b.md](b2c-b2b.md#data-flow).
- Every action takes an optional last parameter `{ emit?: boolean }`, default `true`, and emits its `<feature>.<action>` event from the feature's `constants.ts` when its steps succeed.
- A page model owns what its parts share, such as the current step and the final submit. Each part model owns its part's data and form.
- `http.ts` exports one client, `http.extend(...)`, named after the feature (`catalogHttp`). It may set the base URL, headers, timeout, retry, and feature-only interceptors. It never sets refresh, credentials, or cookie forwarding; the type of `extend` rejects them. Details: [lib-http.md](lib-http.md#root-and-feature-clients).
- Models call repositories directly for queries. Mutations with side effects beyond the request go through an action.
- `*Payload` is the only repository type used outside the repository. If server field names differ from `*Args` names, the mappers translate the server's `fieldErrors` keys too.
- Another feature is imported only through its `index.ts`.
## Shared
```
shared/
├── constants/
│ ├── <constant-name>.ts
│ └── index.ts
├── utils/
│ ├── <util-name>.ts
│ └── index.ts
└── validations/
├── types.ts
├── constants.ts
├── base-validations.ts
├── <feature>-validations.ts
└── index.ts
```
`shared/utils/` holds `apply-server-errors.ts` and `show-action-error.ts`, the two functions every failed action goes through ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)).
`shared/` never imports from `features/`, `stores/`, or `app/`.
## island (`packages/island`)
```
packages/island/src/
├── atoms/
│ └── <component-name>/ # component module
├── molecules/ # like atoms, e.g. empty-state and error-state
├── organisms/
│ └── <component-name>/ # component module + private components/ and hooks/
├── templates/ # 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
│ ├── types.ts
│ ├── constants.ts
│ └── index.ts
├── styles/
│ ├── island.css # entry that apps import into their Tailwind v4 CSS
│ ├── theme.css # primitive and semantic tokens
│ ├── utilities.css # custom @utility definitions
│ └── fonts.css # @font-face rules; root paths to public/fonts/, never relative
├── env/ # island's env: setEnv and getEnv, filled by the app's bootstrap
│ ├── env.ts
│ ├── types.ts
│ └── index.ts
├── icons/
│ ├── symbol-defs.svg # sprite generated by Icomoon; linked as symbol-defs.svg?v=<N>
│ └── selection.json # Icomoon snapshot; re-import it into Icomoon to update the set
├── fonts/ # every app's fonts, e.g. yekan-bakh-vf.woff2
├── constants.ts # island-level constants, e.g. ICON_SPRITE_VERSION, CRITICAL_FONT_URL
├── index.ts
└── server.ts
```
Component module:
| Entry | Required | Holds |
|---|---|---|
| `<ComponentName>.tsx` | Yes | The component |
| `types.ts` | Yes | Every type the component needs, including its props |
| `variants.ts` | Yes | The cva definitions. A non-visual primitive with no styles may skip it |
| `constants.ts` | No | Component-level constants |
| `index.ts` | Yes | The public API, re-exported by name |
| `components/` | Organisms, templates, primitives | Private sub-components shaped like atoms; never imported from outside, except a compound component's named parts, which its `index.ts` re-exports ([design-patterns.md](design-patterns.md)) |
| `hooks/` | Organisms, templates, primitives | Private `use-<hook-name>.ts` hooks |
Tools:
- `icon-sprite-plugin` is a build and dev plugin. It optimizes the SVGs with svgo and writes the final sprite into each app's `public/icons/symbol-defs.svg`.
- `font-copy-plugin` is a build and dev plugin. It copies `fonts/` byte for byte into each app's `public/fonts/`.
- Neither plugin adds a hash or a version to a file name, and no later build step renames their files. The sprite's version lives only in its link ([ui-rules.md](ui-rules.md#fonts-and-the-icon-sprite)). Their output in `public/` is generated, so git ignores it.
- Build-time tools are imported only from build configs, never from app code.
- `icon-name-extraction` extracts icon names from the Icomoon files, for example to type the `Icon` component's `name` prop.
## Choosing where a component goes
Run these three steps for every component you add or move. Write one line per component in the plan: its path, its level, and the reason, for example `packages/island/src/molecules/form-field/: molecule; a label, an input, and an error text for one field; domain-free`.
**1. Reuse.** A component that already does the job is imported, not rebuilt. An island component that does the job but looks different gets a variant in its `variants.ts`, never a new component or a copy.
**2. Level.** Decide by what the component renders and what it imports, never by its size. First match wins.
1. It renders no UI of its own, only structure or behavior (a portal, an error boundary, `LoadOnVisible`) → primitive.
2. It wraps one native element or draws one visual unit, and uses only other atoms (`Button` shows the `Spinner` atom) → atom: `Button`, `Input`, `Badge`, `Icon`, `Skeleton`.
3. It groups atoms for one job and holds no more than UI state, such as open or focused → molecule: `FormField`, `SearchBox`, `EmptyState`.
4. It's a distinct section of a screen: it composes molecules, owns interaction state or a context, or is a compound component → organism: `Tabs`, `DataTable`, `ProductRail`.
5. It arranges organisms into a page layout through slots and holds no data → template, such as a route's mobile or desktop template.
Then check the imports: nothing the component imports sits above its level. A component that needs a higher level belongs at that level. Move it up; never import upward.
**3. Owner.** A component is domain-free when it takes only plain props (strings, numbers, its own prop types, `ReactNode` slots, and callbacks) and imports only island, libs, and tools. It knows a domain when it takes a `*Payload` type, calls a model or an action, reads a store, or shows a feature's text. First match wins.
1. Only one organism, template, or primitive uses it → that module's private `components/`, shaped like an atom.
2. It's a route's mobile or desktop template → that route's `templates/`. When several apps render the same template for that route → `screens/` at that route's path, such as `screens/(auth)/auth/login/templates/`.
3. It knows a domain:
- Navigation UI → `platforms/<platform>/src/app/navigation/components/`.
- Third-party UI, such as a chat widget or its facade → the integration's `components/`.
- One route in one app uses it → that route's `organisms/` in the app.
- Several routes, or the same route in several apps, use it → `platforms/<platform>/src/app/screens/`, in the `organisms/` or `templates/` of the nearest route level they share, such as `screens/(shop)/organisms/`. With no shared level, `screens/organisms/`.
4. It's a domain-free organism that one route uses → that route's `organisms/`. When a second route needs it, move it to island's `organisms/` at once, as [refactoring.md](refactoring.md#when-and-how) describes; never copy it.
5. Otherwise → island, in the folder of its level. Route levels hold only `organisms/` and `templates/`, so every domain-free atom and molecule goes to island at once.
A piece that knows a domain but is smaller than an organism, such as a price line that formats a `*Payload`, is a private component of the organism that uses it. When other code needs it too, give it plain props instead and put it in island. A component that two products need also moves to island with plain props, because one product never imports another's code.
## libs, integrations, and tools packages
```
packages/libs/src/<lib-name>/ # e.g. http, env, error-handler, cookie, local-storage,
├── <lib-name>.ts # pwa, json-ld, custom prototypes, regex, event-emitter
├── types.ts
├── constants.ts
└── index.ts
packages/integrations/src/<integration-name>/ # e.g. sentry, analytics
├── <integration-name>.ts
├── components/ # shaped like organisms
├── hooks/
│ └── use-<hook-name>.ts
├── constants.ts
├── types.ts
└── index.ts
packages/tools/src/<tool-name>/ # shared runtime tools, e.g. use-clock and format-date-time
├── <tool-name>.ts
├── types.ts
├── constants.ts
└── index.ts
```
- libs are framework-agnostic: no React, Next.js, or TanStack imports. They never read env; the app's bootstrap passes their settings through `configure`.
- A lib may split its main file into more files when it grows. `http` does; its layout is in lib-http.md.
- Side-effect modules such as custom prototype extensions must be listed in `sideEffects` (see Exports).
Fundamental libs have full specs:
| Lib | Instance | Owns | Spec |
|---|---|---|---|
| `http` | Root `http`; one `http.extend(...)` client per feature | Every request: verbs, upload and download, interceptors, retry, one refresh at a time on 401, abort, `HttpError`; cookie forwarding on the server | [lib-http.md](lib-http.md) |
| `error-handler` | `configureErrorHandler`, `classifyError`, `describeError`, `handleError` | What each error shows (boundary, empty state, toast), its words and reference ID, its retry kind, and reporting 5xx and logic errors once | [lib-error-handler.md](lib-error-handler.md) |
| `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`, `APPLE_STARTUP_IMAGES`; `writeServiceWorker` (plugin) | The web app manifest's rules, the iOS startup images, 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. `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
1. The app declares its variables in `apps/<app>/src/env/` and validates them with the env lib: `createClientEnv` for public variables and `createServerEnv` for server variables. These files are the only code that reads `process.env`, and a bad variable stops the app with one error that lists every problem. The values come only from the app's `.env` files; only apps have `.env` files, and no project hard-codes an env value, a fallback, or a schema default.
2. Every other project that reads env has `src/env/` (`env.ts`, `types.ts`, `index.ts`) with `setEnv`, which stores its own values, and `getEnv`, which returns them and throws a clear error before `setEnv` has run. Its code reads env only through `getEnv`, inside functions, never at module top level.
3. At startup the app's bootstrap calls each project's `setEnv` with the values that project needs. Projects never import the app, so the dependency graph stays acyclic. Libs never read env: the bootstrap passes their settings through `configure`.
4. `bootstrap.server.ts` fills the server module graph and may pass server-side values, such as an internal service address; `bootstrap.client.ts` fills the client module graph with public values only. Public variables use the `NEXT_PUBLIC_` prefix and are listed one by one in `runtimeEnv`, because Next.js inlines only literal `process.env.NEXT_PUBLIC_*` references.
Code: [lib-env.md](lib-env.md).
## Nx tags and boundaries
Default tags. Reuse the repo's own tags if it already has them.
| Project | Tags |
|---|---|
| `apps/<app>` | `type:app`, `scope:<product>` |
| `platforms/<platform>` | `type:platform`, `scope:<product>` |
| `packages/integrations` | `type:integration`, `scope:shared` |
| `packages/island` | `type:ui`, `scope:shared` |
| `packages/libs` | `type:lib`, `scope:shared` |
| `packages/tools` | `type:tool`, `scope:shared` |
`@nx/enforce-module-boundaries` constraints, the only ESLint rules the repo runs:
| Source tag | May depend on |
|---|---|
| `type:app` | `type:platform`, `type:integration`, `type:ui`, `type:lib`, `type:tool` |
| `type:platform` | `type:integration`, `type:ui`, `type:lib`, `type:tool` |
| `type:integration` | `type:ui`, `type:lib`, `type:tool` |
| `type:ui` | `type:lib`, `type:tool` |
| `type:lib` | `type:tool` |
| `type:tool` | Nothing |
| `scope:<product>` | `scope:<product>`, `scope:shared` |
| `scope:shared` | `scope:shared` |
Layer rules inside a project are checked in review, or by `eslint-plugin-boundaries` when the repo configures it:
- island: no import from a higher atomic level; an organism's `components/` and `hooks/` stay private.
- features: the layer order in Feature anatomy.
- `shared/`: imports nothing above it.
- platform `app/`: `features/`, `stores/`, and `shared/` never import it, so `screens/` stays the UI on top.
## Exports and tree-shaking
Expose each module on its own subpath. With package.json `exports` (Nx workspaces that use TypeScript project references):
```json
{
"name": "@project/island",
"sideEffects": ["**/*.css"],
"exports": {
".": "./src/index.ts",
"./server": "./src/server.ts",
"./atoms/*": "./src/atoms/*/index.ts",
"./molecules/*": "./src/molecules/*/index.ts",
"./organisms/*": "./src/organisms/*/index.ts",
"./templates/*": "./src/templates/*/index.ts",
"./primitives/*": "./src/primitives/*/index.ts",
"./tools/*": "./src/tools/*/index.ts",
"./env": "./src/env/index.ts",
"./styles/*": "./src/styles/*"
}
}
```
Workspaces that use `tsconfig.base.json` path aliases instead map `"@project/island": ["packages/island/src/index.ts"]` and `"@project/island/*": ["packages/island/src/*"]`.
- `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.

View File

@ -1,265 +0,0 @@
# Refactoring
Code smells and refactoring techniques from refactoring.guru, mapped to this architecture. Use this file when code resists a change, while you fix a bug, and in review. It doesn't explain the smells and techniques. It says what each one looks like here and which layer or file the fix belongs in. Pattern choices are in [design-patterns.md](design-patterns.md) and [rendering-patterns.md](rendering-patterns.md). Names match the source pages: refactoring.guru/smells/<smell> and refactoring.guru/<technique>, in kebab-case.
Contents: When and how · Smells that are intended here · Smell catalog · Front-end smells · Techniques used most · Review comments
## When and how
A refactor changes the structure of code and keeps its behavior. Here, behavior also covers what the server renders, what the network sees, and the bundle budgets.
- Never put a refactor in the same commit as a behavior change. Separate commits in one PR are fine. Commit the refactor first, so the behavior change reads as a small diff.
- Cover the behavior first: check it by hand on both templates, mobile and desktop, and say so in the PR. Fix a bug you find this way in a commit of its own. Add a unit test only if the repo already has a unit test runner. The stack has none, so adding one needs approval.
- Take small steps. After each one, type-check, lint, and tests pass for the affected projects through Nx: `nx affected -t <targets>` ([SKILL.md](../SKILL.md#4-workflow)). Never reach green with `any`, a cast, `@ts-expect-error`, or a disabled lint rule.
- Rename symbols and move files with the TypeScript language service (the editor's rename, Move to file, and import updates on file move), never with text replace. Keep the naming rules while you rename: `use-<page>-page.ts`, `<feature>Http`, `*Payload`. The language service can't follow strings such as i18n keys, event names, and route paths, so search for those and check each hit, including every locale's resource file.
- A cookie or storage key is a contract with the server or with data already on users' devices, so renaming one is a behavior change ([lib-cookie.md](lib-cookie.md#keys), [lib-local-storage.md](lib-local-storage.md#keys)).
- A change to a package's public API, such as an island prop or a lib signature, updates every caller in the same PR. `nx affected` then checks every app that uses it.
- To move or rename a whole Nx project, run the Nx move generator (`@nx/workspace:move`), then check the project's tags and its subpath entries (package.json `exports`, or the `tsconfig.base.json` path aliases).
- To move a module into another project, such as a route's organism into island, first check that the target's tags allow every import the module makes. island, for example, imports only libs and tools ([project-structure.md](project-structure.md#nx-tags-and-boundaries)). Then move the files, export the module from the target's `index.ts` (or its `server.ts`, when the module is server-only) and its subpath, and switch every importer to that subpath. Never silence the boundary rule to make a move compile.
- A refactor that spans several features or projects is planned work: give it a written plan and its own PR. Bring legacy code into this architecture one feature at a time, in layer order: entities and repositories first, then actions, models, and UI ([SKILL.md](../SKILL.md#4-workflow)).
- State in the PR description that behavior doesn't change, and how you checked: the check by hand on both templates, and the first-load JS of key routes.
Some moves that look safe change behavior here:
- Hoisting a call to module scope. `getEnv()`, a repository, a cache, `cookie`, or `storage` then runs at import time, which can be before bootstrap or, for `cookie` and `storage`, on the server. On the server, the value it produces is shared by every request ([b2c-b2b.md](b2c-b2b.md#server-and-client-entries)).
- Moving code across a `'use client'` boundary, or importing from a root barrel instead of a subpath. The client bundle changes, so compare the first-load JS of key routes before and after, measured as [b2c-b2b.md](b2c-b2b.md#targets) describes.
- Lifting state to a parent or into a context. The parent re-renders its subtree on each change, and a context re-renders every consumer, so check the INP of the heaviest interaction.
- Extracting a component inside another component's body. It becomes a new component type on every render, so React remounts it and drops its state. Define extracted components at module level.
- Reshaping data that outlives the code: a persisted store's state, which users' devices still hold (bump `version` and add `migrate`, as in [code-patterns.md](code-patterns.md#persisted-store)), or an event's payload, which listeners in other features and integrations read.
- Changing a query key's shape. Invalidation matches keys by prefix, and a part finds its hydrated server data only under the exact key the server used. Change the key factory in the repository's `constants.ts`, never the call sites ([code-patterns.md](code-patterns.md#repository)).
A component that fetches, holds state, and renders is the most common case. Split it in this order, with a green run after each step:
1. Record its behavior by hand on both templates.
2. Move its state, effects, and handlers into a part model (`use-<page>-<part>-part.ts`) as they are, and leave the component presentational.
3. Move the request into a repository method on the feature's client, with its types, mapper, and query key, and read it through `useQuery` in the model. When the first paint or search engines need the data, read it on the server through a cache in `caches/` instead, and pass it as props or prefetch it for query hydration ([b2c-b2b.md](b2c-b2b.md#data-flow)). The HTTP lib and the query cache change retries, errors, and caching, so this step changes behavior: give it its own commit and test the error path.
4. In another behavior commit, add what the rules require and the code lacked, such as a same-size skeleton and a part boundary ([error-handling.md](error-handling.md)).
When to refactor:
- Before a feature the code resists: reshape the code until the feature is a small, obvious edit, then make that edit.
- While fixing a bug, in the layer that owns the fault ([SKILL.md](../SKILL.md#4-workflow)), and only as far as the fix needs.
- In review (see Review comments).
- At the third duplication, not the second (the rule of three), because by then the copies show what actually varies. island is the exception: a component that needs a second style gets an island variant at once, never a copy ([SKILL.md](../SKILL.md#3-architecture-rules)). A route's organism that a second route needs also moves at once, never as a copy: to island when it's domain-free, or to the platform's `screens/`, at the nearest route level both share, when it knows a domain ([project-structure.md](project-structure.md#choosing-where-a-component-goes)).
Refactor only the code the change touches, unless the plan says otherwise. Record other smells you notice as debt in the PR's trade-offs note.
When not to refactor:
- Code that is about to be deleted or rewritten.
- Generated files, such as the icon sprite and Icomoon's `selection.json`. Change their source or their generator instead.
- Library code in `node_modules`. Wrap it instead (see Incomplete Library Class).
- Untested code when there is no time to add a test. Record it as technical debt in the PR instead.
## Smells that are intended here
The catalog would flag these, but the architecture requires them, so never "fix" them. When a tool or a reviewer flags one, point to the reason in the last column.
| What you see | Looks like | Why it stays |
|---|---|---|
| Types-only entities, `*Dto`, and `*Payload` | Data Class | The types carry the back-end contract and the UI's shape; mappers, models, and actions do the work |
| A mapper that copies fields unchanged, or `*Args` and `*Dto` (or `*ResponseDto` and `*Payload`) with the same fields | Duplicate Code | The mapper is where a back-end change stops, so no `*Dto` reaches the UI |
| Named re-exports in every `index.ts` and `server.ts` | Middle Man | They give each module a subpath and keep server-only code out of client bundles. Never collapse them into `export *` |
| `http.extend({})` in a feature that needs nothing special | Lazy Class | Every feature has the same shape, and moving one to its own service is a one-line change ([lib-http.md](lib-http.md#root-and-feature-clients)) |
| A cache that wraps one repository call | Middle Man | Every server reader in the request shares one call ([b2c-b2b.md](b2c-b2b.md#data-flow)) |
| A thin page entry | Middle Man | The entry picks the template and hands it data from the model or the caches, so the logic stays there |
| One-line selector hooks such as `useCurrentUser` | Lazy Class | They hide the store's shape and keep each subscription small |
| Compound components that read their root's private context | Inappropriate Intimacy | The coupling stays inside one organism, and outside code sees only the compound API |
| A mobile and a desktop template per route | Parallel Inheritance Hierarchies | The server picks one per request, so the markup matches on hydration and nothing shifts. This holds only while both templates render from the same models and hold no logic of their own |
| A same-size skeleton beside every part that loads on its own | Parallel Inheritance Hierarchies | It keeps the layout still while the part loads, so nothing shifts or flickers |
| A new endpoint that touches `types.ts`, `mappers.ts`, `constants.ts`, the repository, and `index.ts` | Shotgun Surgery | It is the fixed recipe. Scaffold it with the repo's Nx generator when it has one |
| The `{ emit }` and `{ signal }` options, and an event that nothing listens to yet | Speculative Generality | Actions can run other actions without double events, TanStack Query cancels stale reads, and new listeners never touch the action |
| State styles that no page uses yet, such as `loading` or `selected` | Speculative Generality | island builds every state into the component, so no page can forget one ([SKILL.md](../SKILL.md#3-architecture-rules)) |
| A page model plus one part model per part that loads or changes on its own | Shotgun Surgery | Each part owns its data and form, and the page model owns only what the parts share, such as the current step |
| A `<Suspense>` and a `PartBoundary` around each part that loads on its own | Duplicate Code | One shared boundary would let a slow or failing part block the others |
## Smell catalog
Every smell in refactoring.guru's smell catalog, in its groups. Size thresholds, such as the 80 lines below, are guides, not rules. Before you act on a row, check Smells that are intended here.
### Bloaters
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Long Method | A model hook over about 80 lines; a component that fetches, holds state, and renders; one `useEffect` that does several jobs | Extract Method: part models (`use-<page>-<part>-part.ts`), functions in `mappers.ts` or `shared/utils/`, private components in the organism's `components/`, and one effect per job |
| Large Class | One store that holds several domains; a page model that owns every part's data and form; an organism with many modes and optional props | Extract Class: one store per feature or domain, one part model per part, or a compound component with slots ([design-patterns.md](design-patterns.md)) |
| Primitive Obsession | Statuses and roles typed as `string`; query keys, event names, route paths, and storage keys written as literals at call sites | Replace Type Code with Class: a union in `entities/<entity>/types.ts`, like `OrderStatus`. Replace Magic Number with Symbolic Constant: the owning `constants.ts`, like `productKeys`, `AUTH_EVENTS`, and `ROUTES` |
| Long Parameter List | A repository method or action with several positional parameters; a component with many flat props, often style flags such as `isCompact` and `hideIcon` | Introduce Parameter Object: the endpoint's `*Args`, with options last. For a component: one cva `variant` instead of style flags, `children` or slots, or two components when a flag switches behavior (Replace Parameter with Explicit Methods) |
| Data Clumps | `page`, `pageSize`, `sort`, and filters passed together through models, query keys, and requests; the same address fields in several forms | Introduce Parameter Object: one `*Args` type such as `ListProductsArgs`, which the model builds once and passes whole to the query key and the repository. For forms: one valibot object schema in `shared/validations/` |
### Object-orientation abusers
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Alternative Classes with Different Interfaces | Two components for the same job with different props (`onClose` and `onDismiss`); two repositories that name one operation differently (`fetchAll` and `list`) | Rename Method to one vocabulary, then keep one island component with a variant (Parameterize Method) |
| Refused Bequest | A props type that extends a base type or `ComponentPropsWithRef<'input'>` but neither uses nor forwards most of it (an island atom that spreads the rest onto its native element is fine, as in [code-patterns.md](code-patterns.md#island-component-module)); a `*Payload` declared as its `*ResponseDto` plus extra fields, which hands every server field to the UI | Replace Inheritance with Delegation: `Pick` the props the component uses, and declare the `*Payload` in full so the mapper builds it |
| Switch Statements | The same `switch` or `if` chain on a status, role, or kind in several components, for labels, colors, icons, or allowed actions | Replace Conditional with Polymorphism: one `Record` keyed by the union in the feature's `constants.ts`, a cva variant in island, or one exhaustive `switch` ([design-patterns.md](design-patterns.md)) |
| Temporary Field | State that means something in one mode only, such as `editDraft` that is `null` unless editing, or `uploadProgress` outside an upload | Replace Type Code with State/Strategy: a discriminated union such as `{ status: 'editing'; draft: ProductDraft } \| { status: 'viewing' }`. Move Field into the part model that uses it |
### Change preventers
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Divergent Change | One file edited for unrelated reasons: a catch-all `shared/utils/helpers.ts`, a page model that changes for every part, an island component with branches for one page | Extract Class by reason to change: one util per file, one part model per part. Move Method page-only code into that route's `organisms/`, and give island a variant or a slot instead |
| Parallel Inheritance Hierarchies | Each new status or entity kind needs a matching card, row, and form file; a route's mobile and desktop templates each hold their own logic or data calls | Move Method: the logic into the page or part model, so both templates render one model. When a per-kind split must stay, keep one `Record` per concern keyed by the union, so a missing member fails type-check |
| Shotgun Surgery | One business rule spread across components, validations, and mappers; a cross-cutting concern, such as a header, a log line, or an analytics call, repeated in every repository or action | Move Method and Move Field to one owner: the rule into a model, a util, or a validation; a request concern into the feature's `http.ts` (headers or a feature-only interceptor), or into an interceptor on the root client in bootstrap when every feature needs it ([lib-http.md](lib-http.md#interceptors)); an analytics call into a listener on the action's event, subscribed in the `AppShell`. Inline Class merges scattered fragments |
### Dispensables
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Comments | A comment that explains what a JSX block, an effect, or a condition does | Extract Method into a named hook, component, or predicate, or Extract Variable. Keep comments that explain why, such as a back-end quirk or a browser bug |
| Duplicate Code | Copied JSX or class strings; the same mapping in two mappers; the same query and cache update in several models; a page and its `generateMetadata` that combine the same caches; the same code in two products | A copied or restyled island component: an island variant at once. Other copies, at the third one: an island component, a mapper, a `shared/utils/` function, or a hook in the owning feature's `models/`. A server page loader, `load-<page>-page.ts`, for the page and its metadata ([b2c-b2b.md](b2c-b2b.md#server-and-client-entries)). Parameterize Method when copies differ in one value. Code that two products share moves down to a package, never across to the other product |
| Data Class | The same derivation from a `*Payload`, such as a display name, a total, or a status flag, repeated in several components | Move Method: a field the mapper computes, when every consumer needs it and it doesn't depend on the locale; otherwise a selector hook or a util in the owning feature |
| Dead Code | Exports nobody imports, props no caller passes, cva variants and i18n keys nobody uses, and flag branches that always go one way | Delete it, with Remove Parameter for props and arguments. TypeScript's `noUnusedLocals` and `noUnusedParameters` find unused locals and parameters, and Find All References finds unused exports. knip automates the export search, but it is outside the stack and needs approval |
| Lazy Class | A wrapper component that only forwards props to one island component; a hook or util with one line and one caller | Inline Class or Inline Method into the caller |
| Speculative Generality | A config-driven component or generic hook with one caller; props, variants, or `*Args` fields that nobody passes; a wrapper over TanStack Query or zustand in case the library changes | Inline Class, Inline Method, or Remove Parameter. Add the generality at the third real use |
### Couplers
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Feature Envy | A model or component that computes from another feature's `*Payload` fields or another store's raw state, or builds another feature's query keys by hand | Move Method to the owner of the data: a util or the key factory (such as `productKeys`), exported through that feature's `index.ts`, or a selector hook beside the store in `stores/<store>/` |
| Inappropriate Intimacy | Imports from another feature's internals (its `http.ts`, mappers, or repository folders) or from an organism's private `components/` and `hooks/`; two features that import each other | Import through the owner's `index.ts`, and let Hide Method keep the rest private, or move the shared piece to island or `shared/`. Break a cycle by letting one side react to the other's event (Change Bidirectional Association to Unidirectional) |
| Incomplete Library Class | The same work-around for a library repeated at call sites, such as extra classes that work around tailwind-merge dropping a theme token, identical `toast.error` options, or the same `Intl` setup | Introduce Local Extension: a wrapper like `cn` in island `tools/`; a shared helper that imports no other project, such as the `Intl` formatters, in `packages/tools`; a framework-agnostic library of the kinds [project-structure.md](project-structure.md#libs-integrations-and-tools-packages) lists for `packages/libs`, such as `http`, `cookie`, or `regex`, in `packages/libs`. Introduce Foreign Method: one helper in `shared/utils/`, like `applyServerErrors` |
| Message Chains | Deep paths in components, such as the selector `(state) => state.session?.user.role` repeated across components, or `order.customer.address.city` in JSX | Hide Delegate: a selector hook beside the store, such as `useCurrentUser`, and a flatter `*Payload` built by the mapper |
| Middle Man | A `services/` or `api/` layer between models and repositories; a hook or organism that only forwards to one other | Remove Middle Man: call the repository or render the component directly |
## Front-end smells
The catalog doesn't name these, but this stack has them. Each line gives the smell, the fix, and the rule behind it.
- Props passed down more than two levels → the part reads its own data from its part model or a selector hook, or the parent passes `children` ([SKILL.md](../SKILL.md#3-architecture-rules)).
- State derived from other state, or synced with it, in `useEffect` → derive it during render from props, the query, or a selector. Reset state with a `key` only on a subtree that isn't visible across the change, such as a dialog's form when the dialog opens ([SKILL.md](../SKILL.md#3-architecture-rules)).
- Server state copied into zustand or component state → read it from the query cache through the model ([SKILL.md](../SKILL.md#3-architecture-rules)).
- Several booleans for one flow → one status union with explicit states ([SKILL.md](../SKILL.md#3-architecture-rules)).
- `fetch`, HTTP calls, or data loading in a component or its `useEffect` → a repository method on the feature's client, read through `useQuery` in the model ([lib-http.md](lib-http.md#root-and-feature-clients)); first-paint data goes through a cache on the server ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- Array-index or random keys in a dynamic list → stable ids from the `*Payload` ([SKILL.md](../SKILL.md#3-architecture-rules)).
- One large context → one context per concern.
- A component that subscribes to a whole store → a selector for the smallest slice it renders ([code-patterns.md](code-patterns.md#store)).
- Hard-coded text, colors, or sizes → i18n keys and semantic tokens ([code-patterns.md](code-patterns.md#tokens-and-tailwind-wiring)).
- `'use client'` on a page, layout, or template → only on the interactive leaf, driven by its part model ([b2c-b2b.md](b2c-b2b.md#rendering)).
- Business logic in components → the model, action, mapper, or util that owns it ([SKILL.md](../SKILL.md#3-architecture-rules)).
- Viewport checks choosing layouts → the template the server picks ([b2c-b2b.md](b2c-b2b.md#rendering)).
- A server render that depends on auth (a session read, auth cookies forwarded, a variant picked on the server, or a page that needs a logged-in user rendered on the server) → a browser part, or a page behind the `AuthGuard`, that renders its skeleton until the auth store knows the viewer ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). Leave it when the developer explicitly asked for it and the plan or a decision records it.
- The guest variant shown while the viewer is still unknown → the same-size skeleton while the auth store's `status` is `'unknown'` ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
- A `<Suspense>` boundary or `'use client'` added to keep a part out of the server render → a technique from rendering-patterns.md's "What keeps a part out of the server HTML": browser-only state that renders the skeleton, `next/dynamic` with `ssr: false`, or `LoadOnVisible` ([rendering-patterns.md](rendering-patterns.md#choosing-where-a-part-loads)).
- Cookie or storage reads during render → an effect or an event handler, or `cookies()` on the server passed down as a prop ([lib-cookie.md](lib-cookie.md#browser-only), [lib-local-storage.md](lib-local-storage.md#browser-only)).
- Module-scope data on the server → React `cache()`, props, or the per-request `QueryClient` ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
- A page, loader, or server component that calls a repository directly → a cache, so every reader in the request shares one call ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- A cache called with an object argument, or created inside a component → primitive arguments, and `cache()` defined at module level ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- A store written during server render → props or the query cache, or a store created per request ([b2c-b2b.md](b2c-b2b.md#state-and-auth)).
- `useSuspenseQuery` on a query the server didn't prefetch → `useQuery` with a skeleton ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- A mutation that leaves stale queries, or relies on `staleTime` expiring → set the detail, patch the lists, and invalidate them ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)); also call `router.refresh()` when the change shows in server-rendered content ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
- Query retries on top of the HTTP lib's retries → queries don't retry; `configs/react-query.ts` sets `retry: false` ([lib-http.md](lib-http.md#retry)).
- A refetch that swaps content for a spinner → keep the data and show `isFetching` inline ([ui-rules.md](ui-rules.md#stability)).
- A `catch` that swallows the error or shows a hand-made `toast.error` → in a form, `applyServerErrors`; elsewhere, `showActionError`, which adds the hint or reference ID and the retry the cause allows ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)).
- An `isError` branch in a component, or a toast for a failed read → let the read throw to its part boundary, which shows the fallback or the `not-found` and `no-access` empty states ([error-handling.md](error-handling.md#reads)).
- `handleError`, or a report to the tracker, in a repository, an action, or a `catch` that rethrows → call it once, where the error stops: the fallback, `showActionError`, `QueryCache.onError`, or `onRequestError` ([error-handling.md](error-handling.md#reporting)).
- A server read whose 404 or 403 reaches the browser as a digest → read it through `readOnServer` and decide on the server ([error-handling.md](error-handling.md#b2cb2b-server)).
- An `ABORTED` error shown as a toast or an error state → ignore it ([lib-http.md](lib-http.md#abort)).
- Toasts, navigation, business logic, or store writes in an HTTP interceptor → a model or an action ([lib-http.md](lib-http.md#interceptors)).
- An action that runs another action as one of its steps, emits its own event, and still lets the inner action emit → pass `{ emit: false }` to the inner action, so listeners hear one event per operation ([code-patterns.md](code-patterns.md#action)).
- An event subscription in a component or at module top level, or one without an unsubscribe → subscribe once in an effect of the `AppShell` and unsubscribe in its cleanup ([code-patterns.md](code-patterns.md#action)).
- `process.env` outside the app's `env/` → the app's env, or the project's `getEnv()` inside a function ([lib-env.md](lib-env.md#project-env)).
- A hard-coded env value (an address, key, third-party ID, or flag), a fallback such as `?? 'http://localhost:3000'`, a schema default, or a `.env` file outside an app → a required variable in the app's `.env`, read through the app's env or the project's `getEnv()` ([lib-env.md](lib-env.md#the-apps-env)).
- Navigation through `onClick` and `router.push`, a `<button>`, or a clickable `<div>` → `next/link` or an `<a href>`, so crawlers follow it ([ui-rules.md](ui-rules.md#crawlers)).
- A tab, accordion, drawer, or slider that mounts content that search engines need only when open, or fetches it on click → render it closed and hide it, with `forceMount` on island's `TabsPanel` ([ui-rules.md](ui-rules.md#crawlers)).
- `Date.now()` or `new Date()` in a client component's render, date formatting in a client component whose output the server renders, or a `setInterval` per component → `useClock` behind a same-size skeleton, and dates formatted on the server ([rendering-patterns.md](rendering-patterns.md#time-dependent-ui)).
- A `loading.tsx`, or a `<Suspense>` around `children` in a layout or in a component it renders around them, above an indexable page → a `loading.tsx` only beside a `noindex` or blocked page, or in a route group that holds only such pages ([b2c-b2b.md](b2c-b2b.md#rendering)).
- JSON-LD in a layout, a template, a part, or a client component → JSON-LD in the page entry, before the template ([lib-json-ld.md](lib-json-ld.md#rendering)).
- A page entry, or a Server Component outside a `<Suspense>`, that awaits a read beyond the First flush reads, the reads the primary content needs → a part inside `<Suspense>`, so the status line and the first byte don't wait for it ([b2c-b2b.md](b2c-b2b.md#rendering)).
- A heavy client component that only one template renders, imported statically → `next/dynamic` in a small client component, so only the device that renders it downloads it ([b2c-b2b.md](b2c-b2b.md#rendering)).
Many of these show up in a plain text search, which makes a quick first pass in review: `export *`, `'use client'` in a `page.tsx` or `layout.tsx`, `process.env` outside `env/`, `localhost` or `http` address literals outside an app's `.env`, `fetch(` outside the HTTP lib, `key={index}`, `router.push(` in a card or a list, `isBot` in a page or a template, and `Date.now()` or `new Date()` in a `'use client'` file.
## Techniques used most
Grouped as in refactoring.guru's technique catalog. Each line says how the technique looks in this codebase.
### Composing methods
- Extract Method: extract a function, a hook, or a component. Logic goes to a model hook, a mapper, or a util, markup to a private component, and each job of a long effect to its own effect.
- Inline Method: fold a one-line wrapper hook or util back into its only caller.
- Extract Variable: name a condition before the JSX, or return it from the model: `const canEdit = canUpdate && !order.isLocked;`.
- Replace Temp with Query: derive a value during render from props, the query, or a selector instead of mirroring it in `useState`.
- Remove Assignments to Parameters: never reassign or mutate an argument. Mappers build a new object, interceptors return a new config ([lib-http.md](lib-http.md#interceptors)), and props and query data stay read-only.
- Substitute Algorithm: replace hand-built date and number formatting with `Intl`, using the locale and time zone the server chose ([b2c-b2b.md](b2c-b2b.md#hydration-and-navigation)).
### Moving features between objects
- Move Method and Move Field: move code to the layer that owns it, following the layer order in [project-structure.md](project-structure.md#feature-anatomy). Requests go to a repository, locale-free shaping to a mapper, operations with side effects beyond the request to an action, orchestration to a model, and shared UI to island. State moves down to the component or part model that uses it, or up to the page model when parts share it.
- Extract Class: extract a module, a hook, or a component, such as one store per domain, part models out of a page model, or private components out of an organism.
- Inline Class: merge a module that does almost nothing into its only user.
- Hide Delegate: selector hooks beside the store, such as `useCurrentUser`, so components never walk the store's shape.
- Remove Middle Man: delete pass-through hooks, wrappers, and layers, except the intended ones.
- Introduce Foreign Method: one helper for what a library lacks, in `shared/utils/`, like `applyServerErrors` for react-hook-form and `HttpError`.
- Introduce Local Extension: a wrapper module over a library, like `cn` over clsx and tailwind-merge in island `tools/`. A shared helper that imports no other project goes in `packages/tools`, and a framework-agnostic library of the kinds [project-structure.md](project-structure.md#libs-integrations-and-tools-packages) lists for `packages/libs` goes there.
### Organizing data
- Replace Magic Number with Symbolic Constant: name it in the owning `constants.ts`, like `RELATED_PRODUCTS_LIMIT`. A color, size, or breakpoint becomes a token in island `theme.css` instead.
- Replace Type Code with Class: a string-literal union in the entity, like `OrderStatus`, or an `as const` object when code needs the values at runtime.
- Replace Type Code with Subclasses: a discriminated union with one component per member, chosen through one map.
- Replace Type Code with State/Strategy: a discriminated-union status for a flow, and a `Record` of handlers for behavior that varies per member.
- Encapsulate Collection: only the store's actions change its arrays. Type the arrays `readonly` in the store's `types.ts`. For the persisted cart store in [code-patterns.md](code-patterns.md#persisted-store), its state becomes the one below. As in code-patterns.md, the path is relative to `platforms/<platform>/src/`.
`stores/cart/types.ts`
```ts
import type { CartItemPayload } from '../../features/cart';
export type CartState = {
items: readonly CartItemPayload[];
addItem: (item: CartItemPayload) => void;
clear: () => void;
};
```
Outside the store, `useCartStore.getState().items.push(item)` no longer compiles. Inside `set`, `state.items.push(item)` still does, because immer's draft type drops `readonly`.
### Simplifying conditional expressions
- Decompose Conditional: move each branch of a large conditional JSX block into a named private component, and the condition into a predicate the model returns.
- Consolidate Conditional Expression: one named boolean from the model, such as `canSubmit`, instead of the same chain of checks in several places.
- Replace Nested Conditional with Guard Clauses: early returns right after the component's hook calls for pending, error, and empty. Guard on `isPending`, never on `isFetching`, so a refetch keeps the content.
- Replace Conditional with Polymorphism: a `Record` map, a cva variant, or a discriminated union with one exhaustive `switch` ([design-patterns.md](design-patterns.md)), never a class hierarchy.
- Introduce Null Object: use it only in mappers, for a list the server may leave out (`items: dto.items ?? []`), so the UI never checks for `null`. Never give a query an empty `*Payload` as `initialData`, because the cache treats it as real, fresh data and skips the fetch until `staleTime` ends. Never give one as `placeholderData` either, because the UI would show the empty state while loading. Never replace `session: null` with a guest user, because the guards send a `null` session to login.
- Introduce Assertion: parse data you don't control with a valibot schema instead of an `as` cast, such as `storage.getJSON` results.
### Simplifying method calls
- Introduce Parameter Object: the endpoint's `*Args` type. Repositories take `(args, { signal })` and actions `(args, { emit })`, so a new field changes one type instead of every call.
- Preserve Whole Object: pass the `*Payload` item instead of several of its fields, between server components and inside a module. At a client boundary, pass only what the leaf needs, because props are serialized into the page ([b2c-b2b.md](b2c-b2b.md#rendering)).
- Replace Parameter with Method Call: a part gets its own data from its part model or a selector hook instead of props passed through several levels. What the page model shares still reaches the parts as props.
- Parameterize Method: merge near-identical components into one with a cva variant.
- Replace Parameter with Explicit Methods: split a component whose boolean prop switches its behavior into two components.
- Remove Parameter: delete a prop or `*Args` field that nobody passes. The `{ emit }` and `{ signal }` options stay.
- Separate Query from Modifier: reads live in models as queries. A mutation that only sends the request runs through `useMutation` in the model, and an operation with side effects beyond the request (store writes, storage, follow-up calls, its event) lives in an action. Render, selectors, mappers, and repository read methods never change state.
- Hide Method: keep internals out of `index.ts`. A feature never exports its `http.ts` client or any `*Dto`, and an organism never exports its `components/` or `hooks/`. The one exception is a compound component, whose `index.ts` re-exports its named parts ([design-patterns.md](design-patterns.md)).
- Replace Error Code with Exception: repositories throw the lib's `HttpError` and never return `null`, `false`, or `{ error }` for a failure. Actions let it propagate. For an action, the model catches it: `applyServerErrors` in a form, `showActionError` elsewhere. A failed read throws to its part or page boundary, which shows the `not-found` or `no-access` empty state for 404 and 403 and a fallback with Try again otherwise ([error-handling.md](error-handling.md)). The one place that turns errors back into values is `readOnServer` on the server, because a page must decide between `notFound()`, an empty state, and a boundary before it renders.
### Dealing with generalization
- Extract Interface: a type for a contract with more than one implementation or a test double, like `CookieAdapterAbstraction` ([lib-cookie.md](lib-cookie.md#types)).
- Replace Inheritance with Delegation: compose instead of extending. Use an island component through its `children`, slots, compound parts, or a new island variant, never a feature-level wrapper that restyles it. Build props types from existing ones with `Pick` and `Omit`.
The class-hierarchy techniques rarely apply, because the codebase avoids inheritance. Use these instead:
- Pull Up Method and Pull Up Field: a shared hook, util, or props type.
- Push Down Method and Push Down Field: move the code into the one component, or the field into the one union member, that uses it.
- Extract Superclass and Extract Subclass: a shared hook or base component that others compose, and a specialized component that composes the general one.
- Collapse Hierarchy: one component with a variant instead of near-identical ones.
- Form Template Method: a template with slots, or a hook that takes step callbacks.
## Review comments
Phrase a refactoring finding in the review format from [definition-of-done.md](definition-of-done.md#review): name the smell, or the rule when one is broken; show the problem with its file and its cost; and propose the technique with its target layer or file.
- A smell is a suggestion with a rationale. It blocks a merge only when it also breaks a rule on that section's blocking list, such as a boundary or layer violation or a stale cache after a mutation. Then lead with the rule, mark it blocking, and name the smell in the body.
- In a feature PR, raise smells only in the code the PR touches, and suggest a follow-up PR for the rest.
- Never flag the smells that are intended here.
> **Switch Statements (suggestion):** `OrderRow.tsx`, `OrderCard.tsx`, and `OrderHeader.tsx` each switch on `order.status` to pick a label and a badge color, so a new status needs three edits and nothing checks that all three were made. Replace Conditional with Polymorphism: one `Record` keyed by `OrderStatus`, holding the label key and the Badge variant, in `features/orders/constants.ts` (like `ORDER_STATUS_BADGES` in design-patterns.md), and island's `Badge` `variant` for the color. A new status then fails type-check until the map covers it.
> **Features import each other only through index.ts (blocking):** `features/cart/models/cart/use-cart-page.ts` imports `catalogHttp` and the catalog mappers to load the cart's products itself. That is Inappropriate Intimacy: the request skips catalog's repository, and any change inside catalog can break the cart. Move Method: add `listByIds` to the repository in `features/catalog/repositories/products/`, and import `productsRepository` through `features/catalog/index.ts`.

View File

@ -1,556 +0,0 @@
# Rendering and loading patterns
This file takes the rendering and performance patterns from patterns.dev and decides whether to use each one and which tool implements it. The playbook, [b2c-b2b.md](b2c-b2b.md), holds the details and wins on any conflict. Code-level patterns are in [design-patterns.md](design-patterns.md), and code smells in [refactoring.md](refactoring.md). Names match the source pages under patterns.dev/react/ and patterns.dev/vanilla/.
Contents: Rendering patterns · Auth-dependent UI · Time-dependent UI · Loading patterns · Choosing where a part loads
## Rendering patterns
Apps render every page on the server for each request and stream it. The server render is the same for every visitor: what depends on the viewer renders in the browser (Auth-dependent UI below).
| Pattern | Use | How here |
|---|---|---|
| Client-side rendering | Auth-dependent pages and parts; other browser-only parts | A page or part whose UI depends on the viewer renders completely in the browser (Auth-dependent UI below). Other parts render in the browser only when [b2c-b2b.md](b2c-b2b.md#data-flow) says so. |
| Server-side rendering | Always, for what's the same for every visitor | Render every page fresh for each request, and read data through caches ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). The server render never depends on auth. |
| Static rendering | Never | Nothing renders at build time. Keep each request cheap instead (first note below). |
| Incremental static generation | Never | Nothing needs revalidating: after a mutation, `router.refresh()` renders the page again ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). |
| Partial prerendering | Never | It needs Cache Components, which stay off. `<Suspense>` around slow secondary parts gives an early first paint instead; only `noindex` and blocked pages add a `loading.tsx` ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| Streaming server-side rendering | Always | Stream every route as [b2c-b2b.md](b2c-b2b.md#rendering) describes, and make sure nothing buffers the response (second note below). |
| React Server Components | Default | Keep components on the server. Only interactive leaves get `'use client'` ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| Selective hydration | Automatic | Each part that loads on its own already has its own `<Suspense>`, so it hydrates on its own. Never add a `<Suspense>` only to hydrate a section apart: past React's 12,800-byte limit, it writes the boundary's content after the footer ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| Progressive hydration | Through Suspense | Suspense boundaries already hydrate in pieces. To delay a part's JavaScript, keep its markup in a Server Component and load its client piece on visibility or interaction. A lazy-hydration library would be outside the stack. |
| Islands architecture | Through Server Components | It's unrelated to the island design system; only the name is shared. Server Components with small client leaves give its benefit: only the interactive parts ship JavaScript and hydrate. |
| View transitions | Rare, on Next.js 16.3 or later | React's `<ViewTransition>` with `next/link`'s `transitionTypes`. The App Router ships its own React, so the Next.js version decides: before 16.3 it needs an experimental flag, so wait. Animate only what helps orientation, such as a product image moving into its detail page, and turn it off under `prefers-reduced-motion`. |
- Apps render a fresh page for every request ([b2c-b2b.md](b2c-b2b.md#no-server-cache)), so static rendering, incremental static generation, and partial prerendering are not used. When a page is slow, stream its slow secondary parts, fetch independent data in parallel with `Promise.all`, and fix or cache the slow call in the back end.
- When a developer calls a section "static", it means server HTML that ships no JavaScript, never build-time rendering. A page's rendering doc writes it as HTML `first flush` with JS `none` ([page-rendering.md](page-rendering.md#vocabulary)).
- Streaming works only when nothing between Next.js and the browser buffers the response. Turn buffering off in the reverse proxy and the CDN (for nginx, return `X-Accel-Buffering: no` from `headers()` in `next.config.ts`), or every page waits for its slowest part.
- Experimental APIs, such as `unstable_*` exports, canary-only React features, and Next.js `experimental.*` flags, stay unused until they're stable, unless the repo already enables them. `<ViewTransition>` counts as stable from React 19.3 and Next.js 16.3 (View transitions row). [SKILL.md](../SKILL.md) prefers boring, proven technology.
- Many patterns.dev examples use the Pages Router (`getServerSideProps`, `getStaticProps`, `next/head`), APIs removed in React 19, or libraries such as loadable-components and react-window. Take the idea and write the code with this stack's APIs.
## Auth-dependent UI
The server render never depends on auth. Every visitor of a URL gets the same server HTML, whether they are a guest, a logged-in member, or a paying member.
A page or part is auth-dependent when what it shows changes with who the viewer is: it needs a logged-in user (orders, addresses, settings), it shows a different UI per user type (a guest, a member without a subscription, a member with one), or it shows the viewer's own data (the cart count, a wishlist, recommendations, a member price). Locale, theme, device, and URL parameters aren't auth, so the server may render by them.
- Same for every visitor → render it on the server, through "Choosing where a part loads" below.
- Depends on the viewer → render it completely in the browser. The server renders only its same-size skeleton: it never reads the session, sends auth cookies, or picks a variant. In the browser, the part's model reads the viewer and the viewer's data, and the part renders its variant.
- Render in the browser only the smallest piece that differs. A product page stays on the server and only its membership offer is a browser part. A page renders in the browser as a whole only when all of it depends on the viewer, such as an account page.
- Both are defaults. When the developer explicitly asks for a page or part to render on the server or in the browser, follow the request, state the trade-off, and write the override in the plan. When they make it a lasting rule, record it as a decision ([decisions.md](decisions.md#when-to-record)). Auth-dependent UI rendered on the server needs the auth cookies forwarded and the session refreshed in `proxy.ts` for the whole app, so record that override as a decision even for one page.
Why:
- The server renders the same thing for millions of mostly logged-out visitors, with no per-user back-end calls, so TTFB stays flat.
- The server can't refresh an expired session, because Server Components can't set cookies. A server render that read the session would show a member the guest UI, or fail, whenever the access token expired. In the browser, the HTTP lib refreshes and replays.
- One user's data can never reach another user's HTML through a misconfigured CDN or module state.
- Search engines crawl as guests, so they never saw auth-dependent UI. SEO loses nothing, as long as the guest variant, which Google's renderer shows after JavaScript runs, is a neutral, same-size UI. Never make it an error message or an empty box, which Google may read as a soft 404.
How:
- Server requests forward only the cookies the render needs, never the auth cookies ([b2c-b2b.md](b2c-b2b.md#state-and-auth)), so the back end can't personalize a server response by accident.
- The browser learns who the viewer is once per load. The `AppShell` calls the auth feature's `restoreSession` action in an effect, and the action moves the auth store's `status` from `'unknown'` to `'guest'` or `'member'` ([code-patterns.md](code-patterns.md#store)). The session endpoint answers a guest with an empty session, not 401, so a guest never starts a refresh or a logout. When the read still fails after the HTTP lib's retries, the action clears the session, so the status becomes `'guest'`, and rethrows; the `AppShell`'s effect passes the error to `handleError`.
- An auth-dependent part renders its same-size skeleton while the status is `'unknown'`. That covers the server render and the first browser render, so hydration matches. Never render the guest variant as the placeholder: a member would see it flash, and the layout would shift.
- When the part needs the viewer's own data, its model reads it with `useQuery`, enabled only when the status is `'member'`. Never use a server prefetch or `useSuspenseQuery` for it.
- Every variant ships in the route's bundle. Make a heavy variant, such as a subscriber's video player, a `next/dynamic` component with a same-size `loading` skeleton, so each visitor downloads only their own.
- A page that needs a logged-in user, such as every `(account)` page: the route group's layout wraps its children in the platform's `AuthGuard` (`app/guards/auth-guard/`). This client component renders the page skeleton while the status is `'unknown'`, sends a guest to login with a return URL, and renders the page for a member. The page stays a thin Server Component that resolves the device and passes only URL parameters to its template, and the template's parts load in the browser. That layout's `metadata` export sets `robots: { index: false }`, and each page's `generateMetadata` reads no data: it returns only the generic title in the request's locale ([ui-rules.md](ui-rules.md#metadata-and-viewport)).
- An action that changes the viewer, such as login, logout, or a payment, updates the auth store, so every auth-dependent part renders its new variant. It doesn't call `router.refresh()`, because no server-rendered content changed.
`platforms/<platform>/src/features/membership/models/product/use-membership-offer-part.ts`. A guest sees an invitation to log in, a member without a subscription sees the subscription offer, and a subscriber (`user.hasSubscription`) sees their benefit. `types.ts` declares `MembershipOfferVariant = 'pending' | 'guest' | 'member' | 'subscriber'`.
```ts
import { useCurrentUser, useViewerStatus } from '../../../../stores/auth';
import type { MembershipOfferVariant } from './types';
export function useMembershipOfferPart(): MembershipOfferVariant {
const status = useViewerStatus();
const user = useCurrentUser();
if (status === 'unknown') return 'pending';
if (status === 'guest') return 'guest';
return user?.hasSubscription ? 'subscriber' : 'member';
}
```
`apps/<app>/src/app/(shop)/product/[id]/organisms/membership-offer/MembershipOffer.tsx`. The product template, a Server Component, renders `<MembershipOffer />` beside the server-rendered product summary. The server and the first browser render both show the skeleton. The part reads no data of its own, so it needs no `PartBoundary`; a variant that queries data gets one.
```tsx
'use client';
import { useMembershipOfferPart } from '@project/<platform>/features/membership';
import { GuestOffer } from './components/guest-offer';
import { MemberOffer } from './components/member-offer';
import { MembershipOfferSkeleton } from './components/membership-offer-skeleton';
import { SubscriberOffer } from './components/subscriber-offer';
export function MembershipOffer() {
const variant = useMembershipOfferPart();
if (variant === 'pending') return <MembershipOfferSkeleton />;
if (variant === 'guest') return <GuestOffer />;
if (variant === 'member') return <MemberOffer />;
return <SubscriberOffer />;
}
```
## Time-dependent UI
A part whose output depends on the current time, such as a sale countdown or an open-now badge, can't render its time on the server. The server's clock and the browser's differ, so the hydration render wouldn't match the server HTML. React then throws error #418, renders the nearest `<Suspense>` (or the whole root) again in the browser, and reports an error on every view.
- The server renders the facts that stay true, next to the prices: the sale's end time and the branch's opening hours. Crawlers index these facts, and they match the JSON-LD. The ticking digits are never indexable content.
- Format absolute dates on the server for everything the server renders, with every option pinned, and pass the text down: Node's and the browser's ICU data can format the same date differently. A browser-only part, whose server HTML is its skeleton, such as an account page's order list, formats its dates in the browser with `formatDateTime`. The countdown formats only its digits, with a fixed digit map, not `Intl`.
- The current time comes from `useClock` in `packages/tools/src/use-clock/`: the epoch second or minute, or `null` on the server and in the hydration render. So both renders show the same-size skeleton, and one render right after hydration shows the time, with no mismatch.
- Never read `Date.now()` or `new Date()` while a client component renders, and never hide a clock with `suppressHydrationWarning`: it reaches one level deep and leaves the server's stale text on screen. Never leave out `useSyncExternalStore`'s server snapshot to make a part browser-only: the server render fails, so the nearest `<Suspense>` ships only its fallback and the browser reports error #419 on every view. With no `<Suspense>` above it, as for a section in an indexable page's first flush, the page answers 500 with `noindex`.
- One ticker serves every time-dependent part on the page, so React renders them all in one commit per tick. It ticks on each second boundary and reads `Date.now()` on every tick instead of counting ticks. It stops while the page is hidden and catches up at once when the page shows again, because browsers throttle or freeze timers in hidden tabs. Never give a component its own `setInterval`.
- A part that changes at most once a minute, such as an open-now badge, calls `useClock('minute')` and renders once a minute.
- Use one countdown per sale window: a rail whose offers end together shows one countdown in its header, not one per card.
- At zero, the countdown shows its ended label and announces it once. Nothing refreshes or fetches: every open tab reaches zero in the same second, and each `router.refresh()` is a full server render. Cart and checkout price on the server, and the next page load renders without the sale.
- The countdown's `endsAt`, the `dateTime` of its label's `<time>`, and the offer's `saleEnds` in the JSON-LD are one payload value: an ISO 8601 date-time with its offset ([lib-json-ld.md](lib-json-ld.md#values)). The back end stops sending a sale when the sale ends, so a fresh render never marks up a past date.
- Accessibility: the digits have `role="timer"` and `aria-labelledby` pointing at the visible label, and no `aria-live`, so screen readers never speak every second. Ticking digits are auto-updating content (WCAG 2.2.2, Level A), so users need a control that stops or hides them, or that sets how often they update. Digits that show hours and minutes only still update by themselves, and need the control too; a page that shows only the end time needs none. Record the product's choice as a DDR ([decisions.md](decisions.md)). The `Countdown` below has no such control: build the one the DDR picks before a page renders the digits.
- The skeleton and the digits take the same box: use `tabular-nums`, and check that the font has the `tnum` feature. The skeleton is the digits' glyph pattern in transparent text over the skeleton color, and the ended label shares the digits' grid cell.
`packages/tools/src/use-clock/use-clock.ts`, a generic hook ([design-patterns.md](design-patterns.md#adding-a-pattern)). `types.ts` declares `ClockUnit = 'second' | 'minute'`, and `index.ts` exports `useClock` and `ClockUnit`.
```ts
import { useSyncExternalStore } from 'react';
import type { ClockUnit } from './types';
// One ticker for every time-dependent part on the page, so React renders them all in one commit per tick.
// React calls subscribe and the client snapshots only in the browser, and getServerSnapshot on the server,
// so this module state never holds a request's data.
const listeners = new Set<() => void>();
let second = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const readSecond = () => Math.floor(Date.now() / 1000);
function tick(): void {
second = readSecond();
listeners.forEach((listener) => listener());
// Land on the next second boundary, and read the time again on every tick, so drift never adds up.
timer = setTimeout(tick, 1000 - (Date.now() % 1000));
}
function stop(): void {
clearTimeout(timer);
timer = undefined;
}
// Browsers throttle or freeze timers in hidden tabs: stop while hidden, and catch up at once when visible.
// visibilitychange also fires when the page enters and leaves the back/forward cache.
function onVisibilityChange(): void {
stop();
if (document.visibilityState === 'visible') tick();
}
function subscribe(listener: () => void): () => void {
listeners.add(listener);
if (listeners.size === 1) {
document.addEventListener('visibilitychange', onVisibilityChange);
onVisibilityChange();
}
return () => {
listeners.delete(listener);
if (listeners.size > 0) return;
stop();
document.removeEventListener('visibilitychange', onVisibilityChange);
};
}
// A number that changes once per tick, as useSyncExternalStore needs. With no ticker running
// (before the first subscribe, or while the page is hidden), it reads the time itself.
function getSecond(): number {
if (timer === undefined) second = readSecond();
return second;
}
const getMinute = () => Math.floor(getSecond() / 60);
// The server render and the hydration render both get null, so they match.
const getServerSnapshot = () => null;
// The current epoch second or minute, or null on the server and in the hydration render.
export function useClock(unit: ClockUnit): number | null {
return useSyncExternalStore(subscribe, unit === 'minute' ? getMinute : getSecond, getServerSnapshot);
}
```
`packages/island/src/atoms/countdown/`: an atom with plain props that draws one visual unit. Its `variants.ts` gives `countdownVariants` the base `inline-flex items-center gap-2 tabular-nums` and the sizes `sm` (`text-sm`) and `md` (`text-base`, the default). `index.ts` exports `Countdown`, `CountdownDigits`, `CountdownProps`, `countdownVariants`, and `COUNTDOWN_MAX_MS`. Use it only when the sale ends less than `COUNTDOWN_MAX_MS` (99 hours) after the request, so the hours keep two digits and fit the skeleton's box, even on a browser clock an hour behind the server's. The Server Component that renders it decides, and a later sale shows its end-time label alone. A Server Component may read the clock, because its output never hydrates.
`types.ts`
```ts
import type { VariantProps } from 'class-variance-authority';
import type { ReactNode } from 'react';
import type { countdownVariants } from './variants';
export type CountdownDigits = 'latn' | 'arabext';
export type CountdownProps = VariantProps<typeof countdownVariants> & {
endsAt: string; // ISO 8601 with its offset, the same value as the offer's saleEnds: '2026-10-21T23:59:59+03:30'
label: ReactNode; // rendered on the server: the text and a <time dateTime={endsAt}> formatted on the server
endedLabel: string; // replaces the digits at zero: 'This offer has ended'
digits?: CountdownDigits; // default 'latn'
className?: string;
};
```
`constants.ts`
```ts
import type { CountdownDigits } from './types';
// A fixed map, not Intl: Node's and the browser's ICU data can differ, and the skeleton must match.
export const COUNTDOWN_DIGITS: Record<CountdownDigits, string> = {
latn: '0123456789',
arabext: '۰۱۲۳۴۵۶۷۸۹',
};
// The skeleton has the digits' glyph pattern, so the skeleton and the digits take the same box.
export const COUNTDOWN_PLACEHOLDER = '00:00:00';
// Under 100 hours the hours keep two digits; 99 leaves an hour for a browser clock that runs behind.
export const COUNTDOWN_MAX_MS = 99 * 60 * 60 * 1000;
```
`Countdown.tsx`
```tsx
'use client';
import { useClock } from '@project/tools/use-clock';
import { useId } from 'react';
import { cn } from '../../tools/cn';
import { COUNTDOWN_DIGITS, COUNTDOWN_PLACEHOLDER } from './constants';
import type { CountdownDigits, CountdownProps } from './types';
import { countdownVariants } from './variants';
const pad = (value: number) => String(value).padStart(2, '0');
function formatLeft(seconds: number): string {
return `${pad(Math.floor(seconds / 3600))}:${pad(Math.floor(seconds / 60) % 60)}:${pad(seconds % 60)}`;
}
function toDigits(text: string, digits: CountdownDigits): string {
return text.replace(/\d/g, (digit) => COUNTDOWN_DIGITS[digits][Number(digit)]);
}
export function Countdown({ endsAt, label, endedLabel, digits = 'latn', size, className }: CountdownProps) {
const labelId = useId();
// null on the server and in the hydration render: both show the skeleton, so they match.
const now = useClock('second');
const left = now === null ? null : Math.max(0, Math.floor(Date.parse(endsAt) / 1000) - now);
const hasEnded = left === 0;
return (
<span className={cn(countdownVariants({ size }), className)}>
<span id={labelId}>{label}</span>
{/* The digits and the ended label share one grid cell, so neither change shifts the layout. */}
<span className="grid">
<span
role="timer"
aria-labelledby={labelId}
aria-hidden={left === null || hasEnded || undefined}
dir="ltr"
className={cn(
'col-start-1 row-start-1',
left === null && 'rounded-sm bg-surface-muted text-transparent',
hasEnded && 'invisible',
)}
>
{toDigits(left === null ? COUNTDOWN_PLACEHOLDER : formatLeft(left), digits)}
</span>
<span aria-hidden className={cn('col-start-1 row-start-1', !hasEnded && 'invisible')}>
{endedLabel}
</span>
</span>
{/* Announces the end once; the ticking digits are never announced. */}
<span role="status" className="sr-only">
{hasEnded ? endedLabel : null}
</span>
</span>
);
}
```
`packages/tools/src/format-date-time/format-date-time.ts`, the date formatter that design-patterns.md's Flyweight row puts in `packages/tools`. Server Components call it for everything the server renders; a client component calls it only in a browser-only part, whose server HTML is its skeleton.
```ts
const formatters = new Map<string, Intl.DateTimeFormat>();
// One formatter per locale and time zone (Flyweight), built from the app's constants, never from user input.
// The locale tag pins the calendar and the digits, such as 'fa-IR-u-ca-persian-nu-arabext', so the text
// never depends on the runtime's ICU defaults or its TZ variable.
export function formatDateTime(iso: string, locale: string, timeZone: string): string {
const key = `${locale} ${timeZone}`;
let formatter = formatters.get(key);
if (!formatter) {
formatter = new Intl.DateTimeFormat(locale, { timeZone, dateStyle: 'medium', timeStyle: 'short' });
formatters.set(key, formatter);
}
return formatter.format(new Date(iso));
}
```
`apps/<app>/src/app/(shop)/product/[id]/organisms/product-price/ProductPrice.tsx`, a Server Component, renders the facts and the countdown. `PriceLines` renders the sale price and the struck-through price in the first flush. `getServerI18n` stands for the app's per-request i18next setup in `src/i18n/`, and `DATE_LOCALE` and `STORE_TIME_ZONE` for the app's constants, such as `'fa-IR-u-ca-persian-nu-arabext'` and `'Asia/Tehran'`; match their real names.
```tsx
import { COUNTDOWN_MAX_MS, Countdown } from '@project/island/atoms/countdown';
import { formatDateTime } from '@project/tools/format-date-time';
import { DATE_LOCALE, STORE_TIME_ZONE } from '../../../../../../constants';
import { getServerI18n } from '../../../../../../i18n';
import { PriceLines } from './components/price-lines';
import type { ProductPriceProps } from './types';
export async function ProductPrice({ price, locale }: ProductPriceProps) {
const i18n = await getServerI18n(locale);
const endsAt = price.discountEndsAt;
const label = endsAt && (
<>
{i18n.t('catalog:price.discount-ends')}{' '}
<time dateTime={endsAt}>{formatDateTime(endsAt, DATE_LOCALE, STORE_TIME_ZONE)}</time>
</>
);
return (
<div>
<PriceLines price={price} />
{endsAt &&
// A Server Component may read the clock: its output never hydrates.
(Date.parse(endsAt) - Date.now() < COUNTDOWN_MAX_MS ? (
<Countdown endsAt={endsAt} label={label} endedLabel={i18n.t('catalog:price.discount-ended')} digits="arabext" />
) : (
<p>{label}</p>
))}
</div>
);
}
```
The product page's JSON-LD builder passes the same `price.discountEndsAt` as the offer's `saleEnds` ([lib-json-ld.md](lib-json-ld.md#usage)). The lib writes it as the offer's `validThrough`, and its date as `priceValidUntil`, and `listPrice` becomes the `StrikethroughPrice`. So the markup, the visible end time, and the countdown come from one value in one request.
An open-now badge, `packages/island/src/atoms/open-status/OpenStatus.tsx`, reads the same clock by the minute. The branch's payload gives its opening periods for the next 7 days as ISO instants (`OpenPeriod = { opensAt: string; closesAt: string }`), so the browser does no time-zone math. Its variants give it a minimum width and three statuses, `pending` (transparent text over the skeleton color), `open`, and `closed`, so the skeleton and either label take the same box. The hours table stays in the first flush, formatted on the server.
```tsx
'use client';
import { useClock } from '@project/tools/use-clock';
import { cn } from '../../tools/cn';
import type { OpenStatusProps } from './types';
import { openStatusVariants } from './variants';
export function OpenStatus({ periods, openLabel, closedLabel, className }: OpenStatusProps) {
const minute = useClock('minute');
if (minute === null) {
return (
<span aria-hidden className={cn(openStatusVariants({ status: 'pending' }), className)}>
{openLabel}
</span>
);
}
const now = minute * 60_000;
const isOpen = periods.some(({ opensAt, closesAt }) => Date.parse(opensAt) <= now && now < Date.parse(closesAt));
return (
<span className={cn(openStatusVariants({ status: isOpen ? 'open' : 'closed' }), className)}>
{isOpen ? openLabel : closedLabel}
</span>
);
}
```
## Loading patterns
The budgets these patterns protect are in [b2c-b2b.md](b2c-b2b.md#targets). Record each page's deferred sections and what triggers them in the page's rendering doc ([page-rendering.md](page-rendering.md)).
| Pattern | Use | How here |
|---|---|---|
| Static import | Default | A static import in a `'use client'` file ships to the browser. Put heavy modules behind a dynamic import. |
| Dynamic import | `next/dynamic` in a client component | Select the named export: `.then((mod) => mod.Chart)`. For code that isn't a component, use `await import()` in the event handler. In a `Record` map from key to component inside a client component, such as a CMS block type, make each heavy entry a `next/dynamic` component, so the map doesn't pull every entry into the route's bundle. A map in a Server Component needs nothing: only the client entries it renders ship. |
| Import on visibility | Widgets below the fold | Wrap the lazy component in island's `LoadOnVisible` primitive (code below). |
| Import on interaction | Heavy widgets and embeds | Start the download on `pointerenter` or `focus`, and render on click. A static facade (patterns.dev's word for a placeholder, unrelated to the GoF Facade in design-patterns.md) stands in for video, maps, and chat until then (code below). |
| 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 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 [ui-rules.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. |
| Third-party loading | After hydration | Load from `packages/integrations` with `next/script` and `afterInteractive` or `lazyOnload` ([b2c-b2b.md](b2c-b2b.md#bundle-and-code-splitting)). `@next/third-parties` is outside the stack, and the `worker` strategy is experimental, doesn't work in the App Router, and needs Partytown, which is outside the stack. |
| List virtualization | Long interactive lists, with approval | Paginate on the server and try `content-visibility` first. The library is outside the stack (notes below). |
| Compressing JavaScript | CDN or proxy | Serve Brotli, with gzip as fallback, from the CDN or the reverse proxy. Budgets are measured gzipped. When the proxy compresses, set `compress: false` in `next.config.ts`. |
- On these dynamic routes, `next/link`'s default prefetch stops at the nearest `loading.tsx`, so a click shows the skeleton at once ([b2c-b2b.md](b2c-b2b.md#hydration-and-navigation)). An indexable page has no `loading.tsx`, so a link to it prefetches nothing, and the current page stays until the new one arrives: make every link to an indexable page the platform's `NavLink`, which shows a pending hint inside the clicked link (code below). Never set `prefetch={true}`: every link in the viewport would then ask the server for a full render, and the server caches nothing.
- The LCP image and the critical font follow [ui-rules.md](ui-rules.md#images-fonts-and-css). For anything else, use React 19's resource functions from `react-dom`: `preconnect` for an origin the first screen needs, `prefetchDNS` for one it needs later (such as an embed's host), and `preload` for a critical file the HTML references late. Call them during render or in an event handler; React dedupes the tags.
- Paginate lists on the server first. Give each row of a long, mostly static list a functional utility from island's `styles/utilities.css`, `@utility content-auto-* { content-visibility: auto; contain-intrinsic-size: auto calc(var(--spacing) * --value(integer)); }`, used as `content-auto-16`: off-screen rows skip rendering but stay in the DOM, so find-in-page and screen readers keep working. When an interactive list still renders more than about 200 rows, such as a feed, a log, or a large tree, propose `@tanstack/react-virtual` with the reason and its gzipped size, and add it only after approval ([SKILL.md](../SKILL.md#2-stack)).
`packages/island/src/primitives/load-on-visible/LoadOnVisible.tsx`. It shows the fallback until the element comes within the root margin of the viewport, then renders the children inside `<Suspense>` with the same fallback. The primitive doesn't import `next/dynamic`: the caller passes the lazy component as children, and the import starts when the child first renders. A chunk that fails to load reaches the part's own error boundary.
```tsx
'use client';
import { Suspense, useEffect, useRef, useState } from 'react';
import { LOAD_ON_VISIBLE_ROOT_MARGIN } from './constants';
import type { LoadOnVisibleProps } from './types';
export function LoadOnVisible({ children, fallback, rootMargin = LOAD_ON_VISIBLE_ROOT_MARGIN }: LoadOnVisibleProps) {
const ref = useRef<HTMLDivElement>(null);
const [isNear, setIsNear] = useState(false);
useEffect(() => {
const element = ref.current;
if (isNear || !element) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) setIsNear(true);
},
{ rootMargin },
);
observer.observe(element);
return () => observer.disconnect();
}, [isNear, rootMargin]);
return <div ref={ref}>{isNear ? <Suspense fallback={fallback}>{children}</Suspense> : fallback}</div>;
}
```
The module also has `types.ts` (`LoadOnVisibleProps`: `children`, `fallback`, and an optional `rootMargin`), `constants.ts` (`LOAD_ON_VISIBLE_ROOT_MARGIN = '200px 0px'`), and `index.ts`. It has no `variants.ts`, because it has no styles.
`apps/<app>/src/app/(shop)/product/[id]/organisms/price-history/PriceHistory.tsx`. The product template, a Server Component, renders this client leaf below the fold. Call `next/dynamic` in the same client component as `LoadOnVisible`: a client component that a Server Component imports already ships with the route, so wrapping it would defer only its render. Leave out `ssr: false` here, as [b2c-b2b.md](b2c-b2b.md#data-flow) allows: `LoadOnVisible` or the interaction already keeps the child out of the server render, and with `ssr: false` `next/dynamic` adds its own `<Suspense>` with an empty fallback, which would replace the skeleton or the facade. Where the dynamic component renders unconditionally, keep `ssr: false` and pass `loading: () => <SameSizeSkeleton />`, so its boundary never renders blank.
```tsx
'use client';
import { LoadOnVisible } from '@project/island/primitives/load-on-visible';
import dynamic from 'next/dynamic';
import { PriceHistorySkeleton } from './components/price-history-skeleton';
import type { PriceHistoryProps } from './types';
const PriceHistoryChart = dynamic(() =>
import('./components/price-history-chart').then((mod) => mod.PriceHistoryChart),
);
export function PriceHistory({ productId }: PriceHistoryProps) {
return (
<LoadOnVisible fallback={<PriceHistorySkeleton />}>
<PriceHistoryChart productId={productId} />
</LoadOnVisible>
);
}
```
`apps/<app>/src/app/(shop)/product/[id]/organisms/product-video/ProductVideo.tsx`. One module-level function holds the import, so the facade's intent events (`pointerenter` and `focus`) start the download before the click, and the dynamic component reuses that download. The click sets state inside a transition: React keeps the facade on screen until the chunk arrives, and `isStarting` drives its loading state. The intent download ignores its own failure; the click retries through `next/dynamic`, and a failure there reaches the part's error boundary. A facade lives with its widget, in a route organism or, for a third-party embed such as chat, in the integration's `components/`.
```tsx
'use client';
import dynamic from 'next/dynamic';
import { useState, useTransition } from 'react';
import { useTranslation } from 'react-i18next';
import { VideoFacade } from './components/video-facade';
import type { ProductVideoProps } from './types';
const loadVideoPlayer = () => import('./components/video-player');
const VideoPlayer = dynamic(() => loadVideoPlayer().then((mod) => mod.VideoPlayer));
export function ProductVideo({ video }: ProductVideoProps) {
const { t } = useTranslation('catalog');
const [isPlaying, setIsPlaying] = useState(false);
const [isStarting, startTransition] = useTransition();
if (isPlaying) return <VideoPlayer src={video.url} autoPlay />;
return (
<VideoFacade
posterUrl={video.posterUrl}
label={t('product.video.play', { name: video.title })}
isLoading={isStarting}
onIntent={() => {
loadVideoPlayer().catch(() => undefined);
}}
onPlay={() => startTransition(() => setIsPlaying(true))}
/>
);
}
```
`platforms/<platform>/src/app/navigation/components/nav-link/NavLink.tsx`, the link to every indexable page. It renders `next/link`'s `<Link>` with a pending hint inside, because `useLinkStatus` reads only the nearest `<Link>`: inside a plain `<a>` it always reports idle, and a plain `<a>` loads the whole document. It is navigation UI in the platform rather than in island, because island imports no `next/link`, as `LoadOnVisible` imports no `next/dynamic`. `types.ts` declares `NavLinkProps = ComponentProps<typeof Link>`, and `index.ts` exports `NavLink` and its props type.
```tsx
'use client';
import { cn } from '@project/island/tools/cn';
import Link from 'next/link';
import { LinkPendingHint } from './components/link-pending-hint';
import type { NavLinkProps } from './types';
export function NavLink({ className, children, ...props }: NavLinkProps) {
return (
<Link {...props} className={cn('relative', className)}>
{children}
<LinkPendingHint />
</Link>
);
}
```
`components/link-pending-hint/LinkPendingHint.tsx`, private to `NavLink`. The hint always renders at a fixed size and changes only its opacity, after 100 ms, so it never shifts the layout, and a fast navigation shows nothing.
```tsx
'use client';
import { useLinkStatus } from 'next/link';
import { linkPendingHintVariants } from './variants';
export function LinkPendingHint() {
const { pending } = useLinkStatus();
return <span aria-hidden className={linkPendingHintVariants({ pending })} />;
}
```
`components/link-pending-hint/variants.ts`
```ts
import { cva } from 'class-variance-authority';
export const linkPendingHintVariants = cva(
'pointer-events-none absolute inset-x-0 bottom-0 h-0.5 bg-action-primary transition-opacity',
{
variants: {
pending: {
true: 'opacity-100 delay-100 motion-safe:animate-pulse',
false: 'opacity-0',
},
},
},
);
```
A product card in the platform's `screens/` uses `NavLink` directly. An island organism that renders links to indexable pages, such as `ProductRail`, takes it as a component prop, `linkAs`, and renders each card's link with it. `NavLink` comes from a `'use client'` module, so a Server Component may pass it as a prop: React sends it as a client reference, not as a function.
```tsx
<NavLink href={paths.product(product.id)} className="block">
<ProductCardBody product={product} />
</NavLink>
<ProductRail products={products} linkAs={NavLink} />
```
## Choosing where a part loads
Ask about each part of a page in this order. Step 1 decides first, and every later match adds to the answer, so one part can use several steps: a product gallery renders its first image on the server (2), makes its thumbnails a small client leaf (3), and loads its zoom viewer only when the user opens it (4 and 5). These are defaults: an explicit request from the developer to render a part on the server or in the browser wins (Auth-dependent UI). Data details are in [b2c-b2b.md](b2c-b2b.md#data-flow). Write each answer as the section's HTML and JS values in the page's rendering doc ([page-rendering.md](page-rendering.md#vocabulary)).
1. It depends on the viewer → it renders completely in the browser behind a same-size skeleton, even when search engines or the first paint would want it (Auth-dependent UI). Split off what is the same for every visitor, and ask about that piece from step 2.
2. Search engines or the first paint need it → a Server Component that reads caches. Primary content ([page-rendering.md](page-rendering.md#vocabulary)) renders in the first flush, from the reads the page entry awaits, even when a read is slow: fix the slow read in the back end. Other content streams inside `<Suspense>` with a same-size skeleton when it's slow.
3. The user interacts with it → only the interactive piece becomes a client leaf, driven by its part model, with server data as props or through query hydration.
4. It's below the fold or shown only on interaction, and search engines don't need it → a browser-only part: `useQuery` with a skeleton, or `next/dynamic`: with `ssr: false` when it renders unconditionally, without it inside `LoadOnVisible` or behind an interaction (see the `PriceHistory` note).
5. Its code is heavy, or it's a third party → a dynamic import that starts on visibility or interaction, behind a same-size skeleton or a facade. Third-party scripts use `next/script` with `afterInteractive` or `lazyOnload`.
6. It shows the current time or the time left (a countdown, an open-now badge) → the server renders the facts that stay true (the end time, the opening hours), and a small client leaf reads `useClock` behind a same-size skeleton (Time-dependent UI).
**What keeps a part out of the server HTML.** `'use client'` doesn't, and neither does `<Suspense>`. Client components render to HTML on the server and then hydrate. `<Suspense>` only decides what shows while its children wait: the server streams the fallback, then the children's HTML when they're ready. A child that never suspends still renders on the server: in place while it stays within React's 12,800-byte limit ([b2c-b2b.md](b2c-b2b.md#rendering)), and after the footer above it; and a `useSuspenseQuery` inside it sends its request from the server. Only these keep a part's real UI out of the server HTML:
| Technique | The server HTML holds | Use it for |
|---|---|---|
| Output that depends on browser-only state: the auth store's `status` while it's `'unknown'`, a `useQuery` while it's pending, or `useClock` while it's `null` | The skeleton the component returns | Auth-dependent parts (step 1), data loaded only in the browser (step 4), and time-dependent parts (step 6) |
| `next/dynamic` with `ssr: false` and a same-size `loading` skeleton | The `loading` skeleton | Heavy code that renders at once but the first paint doesn't need (steps 4 and 5) |
| `LoadOnVisible`, or rendering only after an interaction | The fallback or the facade | Parts below the fold or shown on interaction (steps 4 and 5) |
- `ssr: false` throws a bail-out during the server render, so the nearest Suspense boundary sends its fallback. Suspense is how the skip happens, not what causes it.
- React also falls back to client rendering when a child throws during the server render. That's an error path: never use it to keep a part off the server.
- Decide what the server HTML must hold, the real UI or a skeleton, then pick the technique. Add `<Suspense>` only around a part that loads on its own, never around primary content, and never to move a part to the browser.

View File

@ -1,143 +0,0 @@
# UI rules
UX, SEO, and asset rules for [b2c-b2b.md](b2c-b2b.md). Read it when you build or change what the user sees or what search engines read: a page, template, organism, form, copy, upload, image, font, icon, metadata, or viewport. Work only on repositories, caches, actions, stores, or libs doesn't need it.
Contents: Images, fonts, and CSS (Fonts and the icon sprite) · Metadata and viewport · SEO and i18n · Crawlers · Copy · Feedback · Stability · Loading, progress, and empty states · File uploads · Forms · Keyboard and context
## Images, fonts, and CSS
- Use `next/image` with explicit dimensions and `sizes`. Never lazy-load the LCP image: give it `loading="eager"` and `fetchPriority="high"`, or `preload` when it's discovered late. `priority` is deprecated in Next.js 16. Everything below the fold stays lazy.
- Content images are `<img>` elements with a `src`, as `next/image` renders them, never CSS backgrounds: Google indexes images only from `<img>`. Both templates use the same image URLs and alt texts. A gallery or a slider renders every slide's `<img>` in the HTML, and only the first one is eager.
- Fonts come from `island/fonts` as variable woff2. Preload only the critical face, use `font-display: swap`, and give each face a size-adjusted fallback face so the swap doesn't shift layout ([code-patterns.md](code-patterns.md#tokens-and-tailwind-wiring)). Never use `next/font`: it renames the files (next section).
- Reserve space for images, banners, ads, and embeds with fixed aspect ratios.
- Register every project whose components use Tailwind classes as a source (see code-patterns.md).
### Fonts and the icon sprite
Fonts and the icon sprite change rarely, and every page needs them. A hash in their file names changes whenever a build step changes its output, such as a Next.js or svgo upgrade or a new loader option, even when the file itself didn't change. Every visitor then downloads them again. So they keep fixed names, and only a developer decides when visitors download them again.
- Names: fonts keep their own names, such as `yekan-bakh-vf.woff2`, and the sprite stays `symbol-defs.svg`. Each app serves them from `public/fonts/` and `public/icons/`.
- No step adds a hash to them or renames them: not the bundler, not the CSS pipeline, not `next/font` (it copies fonts to `_next/static/media/<hash>.woff2`), not `icon-sprite-plugin`, not a CDN upload. `fonts.css` names each file by its root path, `url('/fonts/yekan-bakh-vf.woff2')`, which Next.js leaves alone. A relative path such as `url('../fonts/...')` goes through the bundler and gets a hash.
- Fonts have no version. A font file never changes under its name: a changed font ships as a new file with a new name.
- The sprite has a version in its link, never in its file name: `/icons/symbol-defs.svg?v=1`. island `constants.ts` holds `ICON_SPRITE_VERSION` and the `ICON_SPRITE_URL` built from it, and the `Icon` atom points `<use href>` at `${ICON_SPRITE_URL}#${name}`. A new Icomoon import or a changed svgo config raises `ICON_SPRITE_VERSION` in the same commit. Never reuse or lower a version.
- The critical font's path lives in island `constants.ts` as `CRITICAL_FONT_URL`, and each root layout preloads it with `preload(CRITICAL_FONT_URL, { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })`. The preload URL must equal the one in `fonts.css`, or the browser downloads the font twice.
- Serve them as immutable. Next.js serves `public/` with `Cache-Control: public, max-age=0`, so the browser asks again on every visit. Add this to the `headers()` in `next.config.ts`, and keep the same header on the CDN. The CDN must keep the query string in its cache key, or a new `?v=` still gets the old sprite.
```ts
const immutable = [{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }];
// inside headers()
{ source: '/fonts/:path*', headers: immutable },
{ 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. The worker checks fonts and the sprite in the background (stale-while-revalidate), so a font changed under its old name reaches each visitor one visit late; a changed font still always gets a new name.
## Metadata and viewport
- Metadata is always in `<head>`. Since Next.js 15.2, metadata streams into `<body>` after the shell, and only a built-in list of HTML-limited bots waits for it in `<head>`. Every app's `next.config.ts` sets that list to every user agent, so crawlers, link previews, and iOS's Add to Home Screen all find the tags in `<head>`:
```ts
htmlLimitedBots: /.*/,
```
- The body still streams: Suspense parts arrive after the first flush as before.
- The cost: the first flush waits for `generateMetadata`, so it becomes the page's TTFB, and on a client-side navigation the page's content waits for it too (a `loading.tsx` still shows at once; a link to an indexable page, which has none, is a `NavLink` that shows a pending hint). Keep it fast: it reads only the caches the page's first paint awaits anyway, so it adds no request.
- A request without a `User-Agent` header still gets streamed metadata.
- Fixed values use the `metadata` export: tags that are the same for every request, such as `robots: { index: false }` in the `(account)` layout, or `APPLE_WEB_APP` in the root layout ([lib-pwa.md](lib-pwa.md#splash-screens)). `generateMetadata` is only for values that depend on the request or on data: params, search params, the locale, or a cache read. The same split holds for `viewport` and `generateViewport`. A segment exports one of each pair, never both: when part of it is dynamic, `generateMetadata` spreads the fixed values from a constant.
- Build metadata 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)).
- Robots tags, the canonical URL, and the title come only from server metadata; only error boundaries render their own `noindex`. Client code never sets, changes, or removes them: Google may skip rendering a page whose server HTML says `noindex`, and it reads the canonical only in `<head>`. So a page that should rank never ships `noindex` to remove it later.
- Every root layout's viewport is `width: 'device-width', initialScale: 1, maximumScale: 1`, kept as `ROOT_VIEWPORT` in `configs/seo.ts`. Next.js renders `<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">`, always in `<head>`, because the viewport never streams. Without `maximum-scale=1`, Safari on iPhone zooms in whenever an input, select, or textarea with text smaller than 16px gets focus, and the page stays zoomed after the keyboard closes. The root layout's `generateViewport` returns `ROOT_VIEWPORT` with the `themeColor` of the theme the server chose; `themeColor` belongs to the viewport, never to `metadata`.
- Accepted trade-off: iOS still lets the user pinch-zoom, but Chrome on Android doesn't unless the user turns on "Force enable zoom", and Lighthouse's `meta-viewport` accessibility audit fails. Reviews don't flag it. Never add `userScalable: false`: it blocks pinch-zoom everywhere else too.
## SEO and i18n
- 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.
## Crawlers
Googlebot Smartphone crawls the mobile template, and Google indexes what it reads there. Google renders JavaScript later, hours later for some pages, or never, and its renderer never clicks, scrolls, types, or keeps cookies. So what search engines need is in each template's server HTML. Each page's rendering doc records where every section stands ([page-rendering.md](page-rendering.md)).
- The first flush of both templates holds the page's primary content: the H1; the main entity's name, price, availability, description, specs, and rating summary; the breadcrumb; the LCP image; the JSON-LD; and the links that are the only path to other pages. Streamed parts hold only secondary content. They sit in a hidden `<div>` at the end of the document until JavaScript moves them, Googlebot reads only the first 2 MB, and a slow part keeps the connection open, which uses up the site's crawl capacity.
- Both templates hold the same primary content and headings, with one H1 that has the same text; the same internal links, image URLs, and alt texts; the same title, description, canonical, and robots tags; and the same JSON-LD and status. A template may collapse or reorder a section that search engines need, but never drop it; only a section they don't need, such as the mobile bottom navigation, may be in one template. Google indexes only the mobile template, and Googlebot Desktop still crawls product pages for Shopping. The breadcrumb shows in both templates, although Google shows it only in desktop results.
- Links that crawlers follow are `<a href>` elements with a real URL in the server HTML: `next/link`, or an anchor. Never navigate with `onClick` and `router.push`, a `<button>`, or a clickable `<div>`, and never fetch menu links on hover or tap: a menu, drawer, or mega menu renders its links in the server HTML and only hides them. A fragment (`#…`) never changes indexable content.
- Collapsed content that search engines need stays in the DOM: tabs, accordions, `<details>`, and sliders render those panels and slides in the server HTML, and only hide them (island's `TabsPanel` takes `forceMount` for this). Never mount such a panel when it opens (`{isOpen && <Panel />}`), and never fetch its content on click: Google sees neither.
- Content that loads on visibility (`LoadOnVisible`) may or may not render for Google, and content that loads on interaction never does. Neither holds primary content or the only link to a page. Never lazy-load what shows when the page opens.
- Pagination: each page has its own URL (`?page=2`) and is its own canonical, and page 1 has one URL, without `?page=1`. Each page links to the previous, the next, and numbered pages with `<a href>` in both templates. "Load more" and infinite scroll fetch the same URLs and update the address with the History API. A page past the last answers 404.
- Filters: decide for each filter whether its URLs are indexable. Indexable filter URLs separate parameters with `&`, keep one parameter order, use one key per filter (`?color=red,blue`), and answer 404 for an empty, duplicate, or unknown combination; internal links always use that form. `robots.ts` disallows every other filter parameter and every sort order on listing paths, and an empty combination that includes one of those parameters answers 200 with the `no-results` empty state and Clear filters.
- Internal search: `robots.ts` disallows `/search` with one rule, and the page sets no robots tag, because Google never fetches a blocked URL to read one. Search never answers 5xx for an unknown query, and category pagination reaches every product without it. `/compare` is disallowed the same way, because every set of products is a new URL. A URL pattern that Google has already indexed gets `noindex` first, and `robots.ts` blocks it only after it drops out of the index.
- `robots.ts` never disallows product, cart, or checkout pages, or the JS and CSS files a template needs. Storebot-Google walks product, cart, and checkout pages to check prices and shipping, and it obeys `User-agent: *` rules; cart and checkout carry `noindex` instead. Add-to-cart works for an automated browser that keeps cookies.
- `sitemap.ts` lists every indexable URL in its canonical form, as a second path for discovery.
- Variants: each variant has its own URL (`?color=green&size=s`), linked with `<a href>`. The server preselects the variant's image, price, and availability from the URL, the canonical drops the variant parameters, and the `ProductGroup` markup stays the same for every variant. `robots.ts` never blocks a variant URL.
- An out-of-stock product stays a 200, indexable page with its stock text, a disabled buy button, and `OutOfStock` in its offer. The status codes for missing, replaced, and empty pages are in [error-handling.md](error-handling.md#b2cb2b-server).
- The URL decides the locale and the currency of an indexable page, never a cookie, `Accept-Language`, or the IP. Googlebot sends no `Accept-Language` and crawls mostly from US addresses, so it would index only one locale.
- Google's renderer keeps no cookies or storage, so viewer-dependent parts render their guest variant for it. Make that variant a neutral, same-size UI, never an error message or an empty box, which Google may report as a soft 404. Every request such a part sends while Google renders the page counts against the API host's crawl budget.
- Under overload, the reverse proxy or the CDN answers crawlers with 503 and `Retry-After`. A 5xx or 429 lowers Google's crawl rate for the whole host.
`apps/<app>/src/app/robots.ts`. `configs/seo.ts` lists `CRAWL_BLOCKED_PARAMS`, the sort, view, and non-indexable filter keys, and `LISTING_PATHS`, the path prefixes of filterable listings, such as `'/category/'`, `'/brand/'`, `'/seller/'`, `'/campaign/'`, and `'/offers'`. The parameter rules name only those paths, because product variant URLs use the same keys (`?color=green&size=s`) and stay open.
```ts
import type { MetadataRoute } from 'next';
import { CRAWL_BLOCKED_PARAMS, LISTING_PATHS } from '../configs';
import { clientEnv } from '../env';
export const dynamic = 'force-dynamic';
export default function robots(): MetadataRoute.Robots {
const params = LISTING_PATHS.flatMap((path) =>
CRAWL_BLOCKED_PARAMS.flatMap((key) => [`${path}*?${key}=`, `${path}*&${key}=`]),
);
return {
// Product pages and their variants, cart, and checkout stay open: Storebot-Google checks prices and shipping there.
rules: { userAgent: '*', disallow: ['/search', '/compare', ...params] },
sitemap: `${clientEnv.NEXT_PUBLIC_SITE_URL}/sitemap.xml`,
};
}
```
## Copy
- Every label, button, tooltip, and message is a simple, complete description of its purpose. Buttons name the action and its object ("Add this item to the cart", not "Add"). Headings describe their content. Tooltips describe the outcome, not the control.
- Error messages have three parts: what went wrong, why (if known), and what the user can do. "The file could not be uploaded because it is larger than 10 MB. Compress the image or choose a smaller file, then try again."
- Empty states say what would normally be here, why it is empty, and the next step, with a primary action when there is one: "Your cart is empty. Browse today's offers to find something you like." plus a "See offers" button.
## Feedback
- Every completed action shows a toast that says exactly what was done, naming the object when possible: "'Wireless headphones' was added to your cart". Success toasts auto-dismiss after 4–6 s. Error toasts come from `showActionError` ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)): they stay until dismissed, name what failed, carry the hint or a support sentence with the reference ID, and offer Try again or Reload when the error's cause allows it.
- Destructive actions ask for confirmation, naming the object and the consequence: "Remove the saved address 'Home'? This cannot be undone."
- Prefer reversible designs: "Undo" in the toast when the back end supports it.
## Stability
Refetches, state updates, and re-renders must never make the UI disappear and reappear.
- Never switch between `isLoading ? <Spinner /> : <List />` on refetch. Keep showing the data with a subtle inline indicator driven by `isFetching`.
- Keep layout containers mounted and swap only their contents.
- Use skeletons with the final content's dimensions, and reserve space for images and embeds with fixed aspect ratios.
- A part whose model uses `useSuspenseQuery` changes its query key inside `startTransition`, so a page or filter change keeps the current content instead of falling back to the skeleton.
## Loading, progress, and empty states
- Design the loading and empty states together with the populated state. Loading states are skeletons that match the final layout. Empty states use island's `EmptyState` (`no-data`, `no-results`, `not-found`, `no-access`) with one sentence and a primary action when there is one ([error-handling.md](error-handling.md#empty-states)).
- Anything that takes more than about 2 seconds shows progress and the current step. Never show a bare spinner for more than 3 seconds.
- The clicked button shows a spinner, becomes disabled, and changes its label to the in-progress form ("Placing order…"). The rest of the form stays visible and read-only.
## File uploads
- Every upload shows a progress bar with a numeric percentage ("Uploading… 63%"), the file name and size, a cancel button while uploading, and a clear success or failure state with a retry action. Uploads go through the feature client's `upload()`: its `onProgress` drives the bar, and the cancel button aborts the `signal`. Uploads never retry automatically; the retry action sends the file again (see [lib-http.md](lib-http.md#files)).
## Forms
- Validate on the client with valibot before submitting, and show errors inline under the field in plain language that says how to fix them ("Enter a 10-digit postal code without spaces."). Validate on blur first, then on change (`mode: 'onTouched'`).
- Put server errors in the right place (code in code-patterns.md) and scroll to and focus the first invalid field.
- Disable the submit button only while submitting, never because the form is invalid; users need to click it to find out what's wrong.
## Keyboard and context
- 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.

View File

@ -1,169 +0,0 @@
---
name: review-fix-loop
description: Run a review-and-fix loop on a path or on a branch's changes vs main. Each round a fresh reviewer subagent reviews the code with the code-review skill and returns severity-tagged findings and a verdict; you fix every blocker and major as the front-end-architect skill, or push back with a concrete reason, run lint, type-check, and tests, and hand the reviewer a changelog. Repeats until the reviewer approves, 5 rounds pass (or the limit the user sets), or a dispute needs the user, then reports every finding's status in a table. Use when the user asks to review and fix, review until approved, run review rounds, iterate on review feedback, or get a branch, PR, or folder merge-ready with a reviewer, even without the word "loop". Not for a one-time review with no fixes (use code-review alone).
---
# Review-fix loop
Run rounds between two roles until the code is approved:
- **Reviewer:** a fresh subagent each round that uses the code-review skill. It sees only the code, its previous round's findings, and your short changelog. It never sees your reasoning, so its approval is an independent check, not an echo of yours.
- **Fixer:** you, acting as the front-end-architect skill. Fixes follow the project's architecture, and every pushback cites something the reviewer can check.
The goal is code the reviewer approves with nothing hidden: no weakened check, no silent change of scope, no disagreement left unstated.
## 1. Setup (once)
1. **Target.** Use the path the user gave. With none, use the changes on this branch vs `main` (use the remote's default branch when there is no `main`).
- Branch: `BASE=$(git merge-base main HEAD)`. The scope is `git diff --name-only $BASE` plus the untracked files in `git status --porcelain`. It holds committed and uncommitted changes, so your fixes stay in view in later rounds.
- Path: the scope is every file under it.
- With an empty scope, tell the user and stop. The scope stays the same for the whole loop; files your fixes touch join it.
2. **Fixer skill.** Load front-end-architect through the Skill tool when it is listed; otherwise read its `SKILL.md` (look in `.claude/skills/`, `~/.claude/skills/`, and `skills/`). Follow its "How to read references": open a reference section only when a fix needs it. If you can't find the skill, tell the user and ask before going on, because fixes and pushbacks depend on its rules.
3. **Checks.** Find the lint, type-check, and test commands for the affected projects. In an Nx repo use `nx affected -t <targets> --base=$BASE`, with target names from `nx show project <name>`; otherwise use the `package.json` scripts. Run them once as a baseline before round 1:
- A failure in a scope file: fix it now, and list it as a pre-loop fix in the report. The reviewer would block it anyway.
- A failure outside the scope (it fails on the base too): show the command and the shortest decisive error line, and ask whether to fix it first or to use "no new failures" as the bar.
- A check the repo doesn't have: note it in the report. Don't invent one.
4. **No commits.** Leave changes in the working tree unless the user asked you to commit. The reviewer reads the working tree.
Keep a ledger through the loop: each finding's ID, severity, status, location or reason, and how many times you disputed it. The final report comes from it.
## 2. Each round
Rounds are numbered 1 to 5, or to the limit the user sets (section 3).
### Step 1: Review
Spawn a new general-purpose subagent (it needs the Skill tool) and wait for its reply. Its prompt is the reviewer brief in section 4, filled in with the round number, the target, and, from round 2, the previous reviewer's reply and your changelog. Pass nothing else: no front-end-architect rules, no plan, no discussion of fixes. Never resume an earlier reviewer, because one that remembers its own reasoning anchors on it. If you can't spawn a subagent, stop and tell the user: reviewing your own fixes defeats the loop.
Check the reply before you use it:
- Every finding has an ID, a severity, a `file:line`, a problem, and a suggested fix, and the last line is a verdict line. If not, ask the same reviewer once to reformat only. That doesn't count as a round.
- The verdict follows the findings: any open blocker or major, new or kept open, means `CHANGES_REQUESTED`, whatever the verdict line says.
Tell the user one line per round: the round, the open findings by severity, and the verdict.
### Step 2: Approved?
If the verdict is `APPROVED`, go to the final report.
### Step 3: Fix
Address every open blocker and major, new or kept open. Each one gets a fix or a dispute.
- **Fix** the problem in the layer that owns it, with the smallest change that resolves it fully and follows front-end-architect's rules. Read the code first. The suggested fix is a suggestion: a different fix that solves the problem is fine, and the changelog says what you did.
- **Dispute** only with a reason a third party can check: a front-end-architect rule (name its section), an accepted entry in `docs/decisions/`, or a fact in the code with its location ("the value is validated at `schemas.ts:12`"). Taste, effort, and "out of scope" are not reasons to leave a real bug. If the reviewer is right, fix it, and tell the user when the fix is large.
- **Minors and nits:** fix one when it is cheap (a few lines, no behavior risk, no new file). Otherwise defer it with a one-line reason. Blockers and majors can't be deferred.
Two rules keep the loop honest:
- Never pass a check by weakening it: no `eslint-disable` or `oxlint-ignore` comments, `@ts-ignore` or `@ts-expect-error`, `as any`, skipped or deleted tests, or loosened assertions. They hide the bug, and the reviewer would flag them anyway. If one really is the right fix, say so in the changelog.
- Change only what a finding asks for. Write other problems you see as follow-ups in the report instead of fixing them silently, so every change the reviewer sees traces to a finding.
**Dispute limit.** If you would dispute a finding that the reviewer already kept open after your earlier dispute, it has stayed disputed for 2 rounds. Finish the round's other fixes and step 4, then stop and ask the user: show the finding, the reviewer's reasoning, your reason, and the options. Don't start another review. The user's decision binds both roles: apply it, write `R1-4 decided by user: <decision>` in the changelog, and continue with the next round if rounds remain.
### Step 4: Verify
Run the baseline checks again. Every check must pass, or show no new failures when the user chose that bar. Fix a failure under the same rules as a finding, then run the checks again. If they still fail after 3 attempts, stop and report: never hand failing code to the reviewer.
### Step 5: Changelog
Write one line for each finding you acted on, in ID order, for the next round:
```
R1-2 fixed in src/atoms/button/Button.tsx:40: the disabled state now sets aria-disabled
R1-4 disputed: island rule "never restyle an island component in a feature; add a variant" (front-end-architect section 3)
R1-6 deferred: renaming the hook touches 12 files outside the scope
```
## 3. Stop conditions
- The verdict is `APPROVED`.
- The last round's review (round 5, or the user's limit) returned `CHANGES_REQUESTED`. Don't fix after the last review: no reviewer would check those fixes, and the report would show unreviewed work as done.
- A finding stayed disputed for 2 rounds. Ask the user (step 3).
- The checks still fail after 3 attempts (step 4).
The limit is 5 rounds. The developer can set another one in the prompt ("at most 3 rounds", "up to 8 rounds").
## 4. Reviewer brief
Fill in the angle brackets. In round 1, delete the parts marked `(round 2+)`; in later rounds, delete only the markers. Send the rest unchanged.
````
You are the reviewer in round <N> of a review-and-fix loop. Another agent fixes the code. You never edit files.
TARGET
<one of:>
- Path: <path>. Review every file under it.
- The changes on this branch vs <base branch>: `git diff <BASE>` for tracked files, plus the untracked files in `git status --porcelain`.
Scope files: <list>
Review the working tree as it is now, committed and uncommitted.
HOW
1. Review the target with the code-review skill (Skill tool, skill "code-review", args: the target<, plus the effort level if the user gave one>). Never pass --fix, --comment, or ultra. The review must cover the whole scope: if code-review's target covers less (for example, only uncommitted changes), review the rest yourself the same way. If the skill is unavailable, review the code yourself for correctness, security, performance, accessibility, and maintainability.
2. Confirm every finding in the code before you report it. Drop what you can't confirm.
3. (round 2+) Check each previous finding in the code itself, not in the changelog's claims:
- Claimed fixed: resolved if the problem is gone and the fix adds no new problem. Otherwise keep it open and say what remains.
- Disputed: accept if the reason holds (read the rule or file it cites). Otherwise keep it open and answer its reason.
- Deferred: accept for a minor or nit. A blocker or major can't be deferred; keep it open.
- Decided by the user: accept.
A previous finding missing from the changelog stays open unless the problem is gone. Never report a previous problem again as new; use its ID.
SEVERITY
- blocker: a bug in a main path, a security hole, data loss, a crash, a broken build or type-check, or a broken project rule that blocks merge (CLAUDE.md, docs/decisions).
- major: a bug in an edge case; a missing error, loading, or empty state; a performance or bundle-size regression; an accessibility failure; a design that will cause bugs.
- minor: works, but worse than it should be: unclear code, small duplication, a missing test for a non-critical path.
- nit: style, naming, taste.
OUTPUT
Reply with only this. Whatever code-review says about reporting, the fixer reads only your final message.
PREVIOUS (round 2+)
- R1-2: resolved
- R1-4: kept open: <reasoning, 1–2 sentences>
- R1-5: dispute accepted: <why>
- R1-6: deferral accepted
NEW
- id: R<N>-1
severity: blocker | major | minor | nit
file:line: <path>:<line>
problem: <1–2 sentences>
suggested fix: <concrete change>
(or "NEW: none")
End with exactly one of these lines:
VERDICT: APPROVED (no blocker or major is open, new or kept open)
VERDICT: CHANGES_REQUESTED (otherwise)
PREVIOUS ROUND'S FINDINGS (round 2+)
<the previous reviewer's reply, verbatim>
CHANGELOG (round 2+)
<your changelog>
````
## 5. Final report
Reply with this, filled in from the ledger:
```
## Review-fix loop: <target>
| ID | Severity | Status | Where fixed / reason |
|---|---|---|---|
| R1-1 | blocker | fixed | src/atoms/button/Button.tsx:40 |
| R1-4 | major | disputed (accepted) | island rule: add a variant, never restyle |
| R2-1 | major | disputed (open) | see Open disagreements |
| R1-6 | nit | deferred | the rename touches 12 files outside the scope |
Rounds: <n> of <limit, 5 by default>. Stopped because: <approved | round limit | dispute needs your decision | checks fail>.
Checks: <commands>: <pass | which failed>.
Changed files (uncommitted): <list>
Open disagreements
- R2-1 (major): <problem>. Reviewer: <reasoning>. Me: <reason>. Decide: <option A> or <option B>.
Follow-ups: <problems seen outside the findings, or "none">
```
Statuses: `fixed`; `disputed (accepted)`, when the reviewer accepted your reason; `disputed (open)`; `deferred`; `decided by user`; and `open`, for a finding unresolved at the round limit or when the checks fail. List pre-loop fixes as their own rows with IDs `pre-1`, `pre-2`. When the loop ends, offer to commit the changes.

View File

@ -24,6 +24,9 @@ const security = [
];
const nextConfig: NextConfig = {
// Set when the panel shares an origin with the market apps under a path (e.g. `/admin`); empty
// in local dev, where the panel has its own port.
basePath: process.env.NEXT_BASE_PATH ?? '',
// Metadata always in <head> (0054).
htmlLimitedBots: /.*/,
experimental: {