chore: update skill

This commit is contained in:
Amiram_se 2026-10-13 23:47:23 +04:00
parent 8c300edf68
commit 7075dfe5c1
16 changed files with 1214 additions and 92 deletions

View File

@ -1,6 +1,6 @@
---
name: front-end-architect
description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites on Next.js App Router (server rendering, 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), and each project's decision records (ADR, DDR). Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, SEO, PWA, or Nx projects, when planning a feature, when the user states a lasting rule or asks to record or change a decision, or when another skill needs front-end input.
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
@ -74,7 +74,8 @@ Any dependency outside this stack needs a stated reason and approval.
**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.
- Client side: repository → model → UI. Every page has a skeleton (`loading.tsx`); every part that loads on its own has its own `<Suspense>` with a same-size skeleton and part boundary (EB-S).
- 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.
@ -84,10 +85,10 @@ Any dependency outside this stack needs a stated reason and approval.
- 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 (locale, theme), never tokens (auth cookies are HttpOnly and server-owned). 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.
- `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, 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.
- 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)**
@ -110,17 +111,17 @@ Any dependency outside this stack needs a stated reason and approval.
## 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; each route's streamed, deferred, and auth-dependent parts; each rendering override the developer asked for; each new non-obvious pattern.
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, and ui-rules.md for UI work (section 5).
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 part, decide whether it depends on the viewer, where it renders, and when its code loads. Add a pattern only for a signal you can name. Refactor code that resists the change first, in its own commit.
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>`). 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.
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
@ -134,6 +135,8 @@ For any design or implementation task, write a short plan in the PR description:
| 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) |

View File

@ -18,8 +18,11 @@ These are defaults; tighten them per product in the plan.
| 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 |
Record the first-load JS of key routes from `next build` in the plan. Any increase on a key route needs a stated reason in the PR.
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
@ -38,7 +41,7 @@ The Next.js server renders a fresh page for every request and keeps nothing betw
},
```
- Every request pays for a full render, so keep it cheap: stream slow parts, fetch in parallel, and when a back-end call is slow, fix or cache it in the back end, never in Next.js.
- 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
@ -46,10 +49,18 @@ The Next.js server renders a fresh page for every request and keeps nothing betw
- 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. Only that view's client code ships, the markup matches on hydration, and nothing shifts. Never choose between layouts with viewport checks in components.
- Stream: add `loading.tsx` per route group and `<Suspense>` with same-size skeletons around slow parts, each inside its own `PartBoundary`. One slow or failing backend call must never block the whole page. Record each route's streamed and auth-dependent parts in the plan.
- 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, outside every `<Suspense>`, from the data its first paint already awaits, so structured data is in the initial HTML and costs no extra request ([lib-json-ld.md](lib-json-ld.md#rendering)).
- 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
@ -66,7 +77,7 @@ The Next.js server renders a fresh page for every request and keeps nothing betw
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 what the first paint needs through caches or a server page loader, and renders the mobile or the desktop template.
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.
@ -82,7 +93,7 @@ A request becomes a page in this order. The server steps run per request, keep n
- 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. Wrap the server component in `<Suspense>` so the await streams.
- 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.
@ -95,7 +106,7 @@ A request becomes a page in this order. The server steps run per request, keep n
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`: the page calls `notFound()` for 404 and 410, 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.
- 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.
@ -104,10 +115,10 @@ The model, the boundaries, and their code are in [error-handling.md](error-handl
- `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 locale and 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.
- 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 (theme, locale) is read on the server with `cookies()` and passed down as a prop.
- 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
@ -121,9 +132,9 @@ The model, the boundaries, and their code are in [error-handling.md](error-handl
## Hydration and navigation
- Render output must be identical on server and client: no `Date.now()`, `Math.random()`, `typeof window` branches, or locale and time-zone differences in render. Format dates and numbers with the locale and time zone the server chose.
- 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.
- 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

View File

@ -21,17 +21,18 @@ Structure
[ ] 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 part went through rendering-patterns.md's "Choosing where a part loads"; every deferred part and its trigger is written in the PR
[ ] 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, from its first-paint data; it says only what the page shows, the same for every visitor; noindex pages and error states have none
[ ] 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 page has a skeleton; every part that loads on its own has its own Suspense skeleton and part boundary (EB-S); the app has EB-W
[ ] 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
@ -54,12 +55,18 @@ Quality
[ ] 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 route's streamed parts are decided and written in the plan
[ ] The server render is the same for every visitor: no session reads, no auth cookies forwarded, no variant picked on the server; auth-dependent parts render their skeleton until the browser knows the viewer, unless the developer asked otherwise
[ ] 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 within budget; heavy widgets and third-party scripts deferred
[ ] 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
@ -79,4 +86,4 @@ Every review comment names the rule, shows the problem, and proposes the fix. Fo
Name a code smell and its technique, with the target layer or file, as [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 page not rendered per request, or a web-vitals or bundle-budget regression. Everything else is a suggestion with a rationale.
Block a merge only for: code that breaks an accepted project decision; a boundary or layer violation; a client-side dependency in a repository; server-only code reachable from a client bundle; tokens or personal data readable by JavaScript (a non-HttpOnly cookie or local storage); stale cache after a mutation; a sprite change without a version bump, a font changed under its old name, or a font or sprite name that a build step hashes; a service worker that stores anything beyond JS, CSS, fonts, and the icon sprite, or a renamed or removed `/sw.js`; structured data that says what the page doesn't show or depends on the viewer, or an `application/ld+json` script written outside island's `JsonLd`; missing error handling; missing loading or empty states; inaccessible contrast; UI that flickers on update; a server-side cache; a server render that depends on auth without the developer's explicit request; a 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

@ -68,7 +68,7 @@ Where a new implementation goes:
| 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` | `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 |
| 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.

View File

@ -269,34 +269,45 @@ export async function readOnServer<T>(read: () => Promise<T>): Promise<ServerRea
}
```
`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)). `getSeller` is a cache, so the metadata and the page share one request, and the cache keeps a failure for the request too.
`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 } from 'next/navigation';
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 readOnServer(() => getSeller(slug));
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(), readOnServer(() => getSeller(slug))]);
if (seller.status === 'not-found') notFound();
if (seller.status === 'no-access') return <StatusEmptyState variant="no-access" size="page" />;
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

View File

@ -22,8 +22,8 @@ Contents: The model · What each failure shows · Boundaries · Reads · Actions
```
- **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 shell, 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 shell, 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)).
- **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.
@ -112,13 +112,35 @@ Rules:
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)).
- `not-found` calls `notFound()`, which renders the group's `not-found.tsx`. When the page has already started streaming (it has a `loading.tsx`), the status stays 200 and Next.js adds a `noindex` robots tag, which search engines treat as not found.
- 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.
@ -153,4 +175,5 @@ The boundaries, `ErrorFallback`, `readOnServer`, and the query client's error se
[ ] 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

@ -6,7 +6,7 @@ Contents: What cookies are for · Structure · Types · API · Keys · Browser o
## What cookies are for
- Only small values the server must see on the request: `locale`, `theme`, and device preference (so the server renders the right version without a flash), and the consent choice.
- 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.

View File

@ -257,7 +257,7 @@ interface DownloadResult {
## 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 `LOCALE_COOKIE` and `THEME_COOKIE`. 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.
- `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)).

View File

@ -16,7 +16,7 @@ Contents: What each page gets · What the markup may say · Structure · Types
| Returns policy | `buildOrganization` with `returnPolicy` | The store's return window and fees on its product results |
| Shipping policy | `buildOrganization` with `shipping` | The store's delivery cost and time on its product results |
| Store branch | `buildStore` and `buildBreadcrumbList` | The branch's address, opening hours, and phone |
| Search results, cart, checkout, account, compare, and every not-found, no-access, or error state | Nothing | Nothing: these pages are `noindex` |
| Search results, cart, checkout, account, compare, and every not-found, no-access, or error state | Nothing | Nothing: these pages are `noindex`, or blocked in `robots.ts` |
- One graph per page: the page passes its nodes to `buildGraph` and renders the result with one `<JsonLd>`.
- The platform's `app/json-ld/` holds one builder per page type that maps a `*Payload`, such as `buildProductPageJsonLd(product)`. The home and policy pages build theirs from the business facts in the app's `configs/seo.ts` (Usage).
@ -25,7 +25,7 @@ Contents: What each page gets · What the markup may say · Structure · Types
Google shows rich results only from markup it trusts, and a manual action for misleading markup makes it ignore the site's markup. So:
- Only what the page shows. The name, price, sale price, availability, rating, review count, reviews, and policies match the server HTML of the same URL. They come from the same `*Payload` in the same request, so they match by construction. Never add a value the page doesn't show; identifiers (`sku`, `gtin`, `mpn`) and the brand may stay invisible.
- Only what the page shows. The name, price, sale price, availability, rating, review count, reviews, and policies match the server HTML of the same URL, in both templates. They come from the same `*Payload` in the same request, so they match by construction. Never add a value the page doesn't show; identifiers (`sku`, `gtin`, `mpn`) and the brand may stay invisible.
- The same for every visitor. Build it only from what the server render reads, never from the viewer: no member price, personal price, cart, or recommendation. A page whose price depends on the viewer, such as a B2B price list after login, has no `offer`; its product can still carry its rating.
- The page's main thing. A product page marks up its product, never the products in its rails, which have their own pages.
- No self-serving ratings. `rating` and `reviews` go on products only, never on the organization or a store: Google ignores what a business shows about itself.
@ -270,7 +270,7 @@ JSON-LD is read by machines in every locale, so its values keep their machine fo
## Rendering
- Where: in the page entry (`page.tsx`), once, before the mobile or desktop template and outside every `<Suspense>`, so it's near the top of the HTML. Google prefers product markup in the initial HTML and reads only the first 2 MB of a page. An element inside `<Suspense>` arrives at the end of the stream, in a hidden `<div>` that client JavaScript moves into place. Never in a layout, where every page under it would repeat it; in a template, which the page has in two versions; in a streamed part; or in a client component, which can't import the lib.
- Where: in the page entry (`page.tsx`), once, before the mobile or desktop template, in the first flush, so it's near the top of the HTML. Google prefers product markup in the initial HTML and reads only the first 2 MB of a page. What streams arrives at the end of the document, in a hidden `<div>` that client JavaScript moves into place. An indexable page has nothing above it that streams, no `loading.tsx` included, so its page entry is always in the first flush ([b2c-b2b.md](b2c-b2b.md#rendering)). Never in a layout, where every page under it would repeat it; in a template, which the page has in two versions; in a part inside `<Suspense>`; or in a client component, which can't import the lib.
- Inside an element: the root layout renders page content inside an element such as `<main>`, so no JSON-LD is a direct child of `<head>` or `<body>`. When the root fails to hydrate, React renders the document again in the browser but keeps the scripts that sit directly under `<head>` and `<body>`, and Google then reads two copies.
- A native `<script>`, never `next/script`: `next/script` adds the element only after hydration, so Google would read it as JavaScript-generated markup.
- From what: only data the page already awaits for its first paint, through the same caches. JSON-LD never waits for a read of its own. Reviews that stream in a part stay out; the product's rating summary is enough for its stars.
@ -891,22 +891,22 @@ export const SEO_SHIPPING = [
] satisfies ShippingServiceInput[];
```
`apps/<app>/src/app/(shop)/page.tsx`, the home page. `getDevice` and the templates are the page's own, as in [page-example.md](page-example.md).
`apps/<app>/src/app/(shop)/page.tsx`, the home page. `getDevice`, `getHomePage`, and the templates are the page's own, as in [page-example.md](page-example.md).
```tsx
import { JsonLd } from '@project/island/primitives/json-ld/server';
import { buildGraph, buildOrganization, buildWebSite } from '@project/libs/json-ld/server';
import { getDevice } from '@project/<platform>/server';
import { getDevice, getHomePage } from '@project/<platform>/server';
import { SEO_ORGANIZATION, SEO_WEBSITE } from '../../configs';
import { HomeDesktop } from './templates/home-desktop';
import { HomeMobile } from './templates/home-mobile';
export default async function HomePage() {
const device = await getDevice();
const [device, home] = await Promise.all([getDevice(), getHomePage()]);
return (
<>
<JsonLd data={buildGraph(buildOrganization(SEO_ORGANIZATION), buildWebSite(SEO_WEBSITE))} />
{device === 'mobile' ? <HomeMobile /> : <HomeDesktop />}
{device === 'mobile' ? <HomeMobile home={home} /> : <HomeDesktop home={home} />}
</>
);
}
@ -962,7 +962,7 @@ export function buildProductPageJsonLd(product: ProductPayload): JsonLdGraph | n
offer: price && {
price: price.selling * RIALS_PER_TOMAN,
listPrice: price.beforeDiscount && price.beforeDiscount * RIALS_PER_TOMAN,
saleEnds: price.discountEndsAt,
saleEnds: price.discountEndsAt, // the countdown's endsAt too, so the markup and the page end together
priceCurrency: PRICE_CURRENCY,
availability: STOCK_AVAILABILITY[product.stock],
},
@ -981,20 +981,7 @@ import 'server-only';
export { buildProductPageJsonLd } from './product-json-ld';
```
`apps/<app>/src/app/(shop)/product/[id]/page.tsx`, the page from [page-example.md](page-example.md) with its JSON-LD:
```tsx
export default async function ProductPage({ params }: ProductPageProps) {
const { id } = await params;
const [device, product] = await Promise.all([getDevice(), getProduct(id)]);
return (
<>
<JsonLd data={buildProductPageJsonLd(product)} />
{device === 'mobile' ? <ProductMobile product={product} /> : <ProductDesktop product={product} />}
</>
);
}
```
`apps/<app>/src/app/(shop)/product/[id]/page.tsx` renders the graph in its page entry, before the template, for an `ok` read only, as [page-example.md](page-example.md) shows: `<JsonLd data={buildProductPageJsonLd(product.data)} />`.
## Testing and monitoring

View File

@ -1,6 +1,6 @@
# Page example: caches, page, and parts
A full page for [b2c-b2b.md](b2c-b2b.md): device detection, caches, a server page loader, the page entrypoint with its JSON-LD, streamed parts, and query hydration. Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet. Otherwise copy the shape of an existing page.
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`
@ -9,10 +9,39 @@ import 'server-only';
import { headers } from 'next/headers';
import { userAgent } from 'next/server';
export async function getDevice(): Promise<'mobile' | 'desktop'> {
const { device } = userAgent({ headers: await headers() });
return device.type === 'mobile' ? 'mobile' : 'desktop';
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`
@ -45,40 +74,60 @@ export { getProduct, getProductReviews, getRelatedProducts } from './products';
```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`. `generateMetadata` and the page both call `getProduct(id)`, and the cache sends one request. The page renders its JSON-LD from the same product, beside the template and outside every `<Suspense>`; `buildProductPageJsonLd` is in [lib-json-ld.md](lib-json-ld.md#usage). A page whose main read can answer 404 or 403 reads through `readOnServer` instead, as the seller page in [error-handling-code.md](error-handling-code.md) does, and renders JSON-LD only for an `ok` read.
`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 { buildProductPageJsonLd, getDevice, getProduct } from '@project/<platform>/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 getProduct(id);
return { title: product.name, description: product.summary };
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(), getProduct(id)]);
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)} />
{device === 'mobile' ? <ProductMobile product={product} /> : <ProductDesktop product={product} />}
<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
@ -98,16 +147,19 @@ The desktop template, a Server Component, renders the product at once and stream
`.../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} />;
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

View File

@ -0,0 +1,397 @@
# 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

@ -0,0 +1,249 @@
# 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

@ -15,6 +15,9 @@ packages/
├── 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:
@ -67,6 +70,7 @@ apps/<app>/src/
```
- Pages are thin entrypoints. A page picks the mobile or the desktop template on the server, so no component branches on viewport size.
- 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`.
@ -100,7 +104,7 @@ platforms/<platform>/src/
│ │ ├── types.ts
│ │ ├── hooks/
│ │ │ └── use-<hook-name>.ts
│ │ ├── components/ # navigation UI, shaped like organisms
│ │ ├── 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
@ -308,7 +312,7 @@ packages/integrations/src/<integration-name>/ # e.g. sentry, analytics
├── types.ts
└── index.ts
packages/tools/src/<tool-name>/ # shared runtime tools
packages/tools/src/<tool-name>/ # shared runtime tools, e.g. use-clock and format-date-time
├── <tool-name>.ts
├── types.ts
├── constants.ts

View File

@ -22,7 +22,7 @@ A refactor changes the structure of code and keeps its behavior. Here, behavior
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 from `next build` before and after ([b2c-b2b.md](b2c-b2b.md#targets)).
- 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.
@ -65,7 +65,7 @@ The catalog would flag these, but the architecture requires them, so never "fix"
| 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, so only that view's code ships. This holds only while both templates render from the same models and hold no logic of their own |
| 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 |
@ -163,8 +163,15 @@ The catalog doesn't name these, but this stack has them. Each line gives the sme
- 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, and `key={index}`.
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

View File

@ -2,7 +2,7 @@
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 · Loading patterns · Choosing where a part loads
Contents: Rendering patterns · Auth-dependent UI · Time-dependent UI · Loading patterns · Choosing where a part loads
## Rendering patterns
@ -14,15 +14,16 @@ Apps render every page on the server for each request and stream it. The server
| 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. `loading.tsx` and `<Suspense>` give an early first paint instead ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| 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 | Give each independent part its own `<Suspense>` boundary, so it hydrates on its own ([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 parts, fetch independent data in parallel with `Promise.all`, and fix or cache the slow call in the back end.
- 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.
@ -43,7 +44,7 @@ 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.
- 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:
@ -90,9 +91,273 @@ export function MembershipOffer() {
}
```
## 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 route's deferred parts and what triggers them in the plan (the PR description).
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 |
|---|---|---|
@ -111,7 +376,7 @@ The budgets these patterns protect are in [b2c-b2b.md](b2c-b2b.md#targets). Reco
| 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)). Never set `prefetch={true}`: every link in the viewport would then ask the server for a full render, and the server caches nothing.
- 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)).
@ -205,24 +470,87 @@ export function ProductVideo({ video }: ProductVideoProps) {
}
```
`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).
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, inside `<Suspense>` with a same-size skeleton when it's slow.
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 renders on the server as if the boundary weren't there, and a `useSuspenseQuery` inside it sends its request from the server. Only these keep a part's real UI out of the server HTML:
**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'`, or a `useQuery` while it's pending | The skeleton the component returns | Auth-dependent parts (step 1) and data loaded only in the browser (step 4) |
| 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>` for streaming and selective hydration, never to move a part to the browser.
- 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

@ -2,11 +2,12 @@
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 · Copy · Feedback · Stability · Loading, progress, and empty states · File uploads · Forms · Keyboard and context
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).
@ -41,10 +42,11 @@ const immutable = [{ key: 'Cache-Control', value: 'public, max-age=31536000, imm
```
- 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 (`loading.tsx` still shows at once). Keep it fast: it reads only the caches the page's first paint awaits anyway, so it adds no request.
- 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.
@ -53,6 +55,47 @@ const immutable = [{ key: 'Cache-Control', value: 'public, max-age=31536000, imm
- 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.