diff --git a/.claude/skills/front-end-architect/SKILL.md b/.claude/skills/front-end-architect/SKILL.md index c09a51b..d12dde2 100644 --- a/.claude/skills/front-end-architect/SKILL.md +++ b/.claude/skills/front-end-architect/SKILL.md @@ -1,6 +1,6 @@ --- name: front-end-architect -description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites (Next.js App Router, server rendering, web vitals, bundle and hydration budgets for millions of daily visitors). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and token refresh; error handler; env; cookie; local storage), integrations, and tools, with kebab-case naming, tree-shakeable exports with server and client entries, and DDD features (entities, repositories, caches, actions, models), on Tailwind v4 with cva, valibot, react-hook-form, zustand, i18next, and sonner. Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects in these monorepos, when planning a feature, or when another skill such as a product designer or architect needs front-end input. +description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites (Next.js App Router, server rendering, web vitals, bundle and hydration budgets for millions of daily visitors). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and token refresh; error handler; env; cookie; local storage), integrations, and tools, with kebab-case naming, tree-shakeable exports with server and client entries, and DDD features (entities, repositories, caches, actions, models), on Tailwind v4 with cva, valibot, react-hook-form, zustand, i18next, and sonner, and keeps each project's architecture and design decision records (ADR, DDR). Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects in these monorepos, when planning a feature, when the user states a lasting project rule or asks to record or change a decision, or when another skill such as a product designer or architect needs front-end input. --- # Front-end Architect @@ -11,7 +11,8 @@ How you work: - Explain *why*, not only *what*. Present designs and reviews as checklists. - When a requirement is ambiguous, state your assumption and continue. Ask only when a wrong guess would be expensive to undo. -- When a request conflicts with a rule here, follow the rule and explain the trade-off. When something isn't covered, reason from these principles and say so. +- When a request conflicts with a rule here, follow the rule and explain the trade-off, unless an accepted project decision overrides it. When something isn't covered, reason from these principles and say so. +- Follow the project's decisions. When `docs/decisions/README.md` exists, read it once per session before any task: each line is one rule. When the user states a lasting rule, or you make a choice that is hard to undo, record it as [references/decisions.md](references/decisions.md) describes. - Prefer boring, proven technology, fewer re-renders, and the user's time. ## 1. The project @@ -64,7 +65,7 @@ Error handling, patterns, and refactoring have their own references. Read each o - Error handling (error boundaries EB-W and EB-S, API errors by status for reads and actions, empty states, reporting), before you add a page, a part, a query, an action, or a form, and whenever code catches or shows an error: [references/error-handling.md](references/error-handling.md) - Design patterns (GoF, JavaScript, and React: which one, where it lives, its shape, and what isn't used), before you add a pattern or a shared abstraction such as a factory, a `Record` map, a state machine, an adapter, a context, or a generic hook: [references/design-patterns.md](references/design-patterns.md) -- Rendering and loading patterns, before you add or move a part of a page or change when its code loads: [references/rendering-patterns.md](references/rendering-patterns.md) +- Rendering and loading patterns, before you add or move a part of a page, or change where it renders or when its code loads: [references/rendering-patterns.md](references/rendering-patterns.md) - Code smells and refactoring (safe steps, smells mapped to layers, smells that are intended), before you refactor and when you review code, together with design-patterns.md's "Not used here" list: [references/refactoring.md](references/refactoring.md) **Naming** @@ -96,6 +97,13 @@ Error handling, patterns, and refactoring have their own references. Read each o - `stores/` sits beside `features/`: zustand + immer, one store per feature or domain, holding `*Payload` data. - `shared/` holds `constants/`, `utils/`, and `validations/` (valibot: `base-validations.ts` plus one `-validations.ts` per feature). +**Rendering and auth** + +- The server render never depends on auth. It reads no session and sends no auth cookies, so every visitor of a URL gets the same server HTML. +- A page or part whose UI depends on the viewer renders completely in the browser. That covers pages that need a logged-in user, UI that differs for guests, members, and paying members, and the viewer's own data. The server renders only its same-size skeleton, and the skeleton stays until the browser knows who the viewer is. Render in the browser only the smallest piece that differs. +- A page or part that is the same for every visitor renders on the server. +- Both are defaults. When the developer explicitly asks for a page or part to render on the server or in the browser, follow the request, state the trade-off, and write it in the plan. Details: [references/rendering-patterns.md](references/rendering-patterns.md#auth-dependent-ui). + **Data flow** - Client side (the parts of a page that load in the browser): repository → model → UI. Every page has a skeleton (`loading.tsx`). Every part that loads on its own has its own `` with a same-size skeleton and its own part boundary (EB-S), so one slow or failing part never blocks the others. @@ -105,7 +113,7 @@ Error handling, patterns, and refactoring have their own references. Read each o - Env (`packages/libs/src/env`): only the app's `env/` files read `process.env`, through `createClientEnv` (public) and `createServerEnv` (server only). Other projects read their own values with `getEnv`, filled by the app's bootstrap. Libs never read env; the bootstrap passes their settings through `configure`. - HTTP (`packages/libs/http`): one root `http` client, configured in the app's bootstrap, and one client per feature made with `http.extend(...)`, so every feature shares one token refresh, the interceptors, and error normalization. - - Auth is cookie-based. On a 401, one refresh runs for the whole app, the waiting requests replay once, and a failed refresh triggers logout. The server side never refreshes. + - Auth is cookie-based. On a 401, one refresh runs for the whole app, the waiting requests replay once, and a failed refresh triggers logout. The server side never refreshes and never sends the auth cookies. - Retry covers only idempotent requests, with backoff. Every request is abortable, and aborted requests are silent. Uploads report progress. - Every failure is an `HttpError`: `{ code, message, status, fieldErrors, hint, requestId, retryAfter }`. The error handler lib (`packages/libs/error-handler`) decides what each one shows and reports it. - Cookies (`packages/libs/cookie`, the `cookie` instance): only small values the server needs on the request, such as locale and theme. Never tokens: auth cookies are HttpOnly and belong to the server. Browser only; server code reads cookies with `next/headers`. @@ -131,12 +139,12 @@ Error handling, patterns, and refactoring have their own references. Read each o ## 4. Workflow -Follow these steps for any design or implementation task. Write a short plan in the PR description: affected projects and paths, data types, each route's streamed and deferred parts, and each new non-obvious pattern. +Follow these steps for any design or implementation task. Write a short plan in the PR description: affected projects and paths, data types, each route's streamed, deferred, and auth-dependent parts, each rendering override the developer asked for, and 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** ([b2c-b2b.md](references/b2c-b2b.md)), plus [ui-rules.md](references/ui-rules.md) for UI work. 3. **Map the data.** Entities, repository types (`*Args`, `*Dto`, `*ResponseDto`, `*Payload`), caches and how each client part gets its server data, page and part models, actions and their events, query keys, and how the query cache is updated after each mutation. -4. **Place the code.** List the Nx projects and folders that change. Reuse what exists before creating anything. For each part you add or move, decide where it renders and when its code loads ([rendering-patterns.md](references/rendering-patterns.md)), and add a pattern only for a signal you can name ([design-patterns.md](references/design-patterns.md)). When existing code resists the change, refactor it first, in its own commit ([refactoring.md](references/refactoring.md)). +4. **Place the code.** List the Nx projects and folders that change. Reuse what exists before creating anything. For each part you add or move, decide whether it depends on the viewer, where it renders, and when its code loads ([rendering-patterns.md](references/rendering-patterns.md)), and add a pattern only for a signal you can name ([design-patterns.md](references/design-patterns.md)). When existing code resists the change, refactor it first, in its own commit ([refactoring.md](references/refactoring.md)). 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, adding variants to island when needed: 1. Setup: Nx projects, tags, subpath exports, and new env variables. @@ -180,7 +188,9 @@ Structure [ ] 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 +[ ] 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 [ ] 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 @@ -204,4 +214,4 @@ Every review comment names the rule, shows the problem, and proposes the fix. Fo Name a code smell and its technique, with the target layer or file, as [references/refactoring.md](references/refactoring.md#review-comments) does. A smell is a suggestion; when it also breaks a rule on the list below, lead with that rule, mark it blocking, and name the smell in the body. In a feature PR, raise smells only in the code the PR touches. Flag a pattern from the "Not used here" list in [references/design-patterns.md](references/design-patterns.md#not-used-here) with its alternative. Never flag the smells that refactoring.md marks as intended. -Block a merge only for: 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; missing error handling; missing loading or empty states; inaccessible contrast; UI that flickers on update; a server-side cache; 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; 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. diff --git a/.claude/skills/front-end-architect/references/b2c-b2b.md b/.claude/skills/front-end-architect/references/b2c-b2b.md index 63af98a..a04c652 100644 --- a/.claude/skills/front-end-architect/references/b2c-b2b.md +++ b/.claude/skills/front-end-architect/references/b2c-b2b.md @@ -33,10 +33,11 @@ The Next.js server renders a fresh page for every request and keeps nothing betw ## Rendering - Server Components by default. Put `'use client'` only on interactive leaves, never on a layout or page. +- The server render never depends on auth: every visitor of a URL gets the same server HTML. A page or part whose UI depends on the viewer (it needs a logged-in user, differs for guests, members, and paying members, or shows the viewer's own data) renders completely in the browser behind a same-size skeleton. What is the same for every visitor renders on the server. An explicit request from the developer overrides either default ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). - Templates stay Server Components. Interactive parts are small client components, each driven by its part model (`use---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 `` 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 parts in the plan. +- Stream: add `loading.tsx` per route group and `` with same-size skeletons around slow parts, each inside its own `PartBoundary`. One slow or failing backend call must never block the whole page. Record each route's streamed and auth-dependent parts in the plan. - Server code reads data through the features' caches, so `generateMetadata`, the page, and every server component share one request per distinct call (see Data flow). ## Server and client entries @@ -51,13 +52,12 @@ The Next.js server renders a fresh page for every request and keeps nothing betw ## Data flow -A request becomes a page in this order. The server steps run per request and keep nothing afterwards. +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. `proxy.ts` refreshes an expired session before rendering. -2. Every root layout imports `bootstrap.server.ts` first. -3. 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. -4. Server components that need more data read it through caches. A slow part is an async server component inside `` with a same-size skeleton, so the page streams around it. -5. 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. After a mutation that changes server-rendered content, `router.refresh()` renders the page again. +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. +3. Server components that need more data read it through caches. A slow part is an async server component inside `` with a same-size skeleton, so the page streams around it. An auth-dependent part renders only its skeleton on the server. +4. Client components get server data as props or through query hydration (below). In the browser their models take over: queries through repositories, mutations through actions, and auth-dependent parts render their variant once the auth store knows the viewer. After a mutation that changes server-rendered content, `router.refresh()` renders the page again. **Caches** (`features//caches/`, server-only) @@ -77,14 +77,14 @@ A request becomes a page in this order. The server steps run per request and kee **Data loaded only in the browser** -- Render on the server what search engines and the first paint need. Load in the browser only what's personal, below the fold, or shown on interaction, through a part model inside `` with a skeleton. +- Render on the server what search engines and the first paint need. Load in the browser only what depends on the viewer, is below the fold, or is shown on interaction, through a part model inside `` with a skeleton. - A browser-only part uses `useQuery` and shows its skeleton while pending, or is loaded with `next/dynamic` from a client component: with `ssr: false` and a same-size `loading` skeleton when it renders at once, and without `ssr: false` when `LoadOnVisible` or an interaction already delays it ([rendering-patterns.md](rendering-patterns.md)). `useSuspenseQuery` is only for queries the server prefetched: any other query would run during SSR, where requests carry none of the user's cookies. ## Errors The model, the boundaries, and their code are in [error-handling.md](error-handling.md). What is special here: -- Server reads classify on the server, because a Server Component error reaches the browser with only its digest. Pages and server parts read through `readOnServer`: the page calls `notFound()` for 404 and 410, renders the `no-access` empty state for 403 with `robots: { index: false }`, and redirects a 401 to login; 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`: 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. - 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. @@ -93,9 +93,9 @@ 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 the incoming request's 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. That configures the root client, so every feature client forwards cookies too. 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 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. - 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)). -- Server Components can't set cookies. Refresh an expired session in `proxy.ts` before rendering, or in a Route Handler or Server Function, never during render. +- 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. - 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). @@ -136,6 +136,7 @@ In [page-example.md](page-example.md). Read it when you add a new page, or a par [ ] 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 [ ] 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' diff --git a/.claude/skills/front-end-architect/references/code-patterns.md b/.claude/skills/front-end-architect/references/code-patterns.md index 114b36a..3306ea8 100644 --- a/.claude/skills/front-end-architect/references/code-patterns.md +++ b/.claude/skills/front-end-architect/references/code-patterns.md @@ -152,6 +152,7 @@ This is an excerpt. The real file defines every semantic token the components us ```css @import './theme.css'; +@import './fonts.css'; @import './utilities.css'; @source '../'; ``` @@ -527,7 +528,10 @@ export type Session = { isFirstLogin: boolean; }; +export type ViewerStatus = 'unknown' | 'guest' | 'member'; + export type AuthState = { + status: ViewerStatus; session: Session | null; setSession: (session: Session) => void; clearSession: () => void; @@ -543,23 +547,30 @@ import type { AuthState } from './types'; export const useAuthStore = create()( immer((set) => ({ + status: 'unknown', session: null, setSession: (session) => set((state) => { + state.status = 'member'; state.session = session; }), clearSession: () => set((state) => { + state.status = 'guest'; state.session = null; }), })), ); export const useCurrentUser = () => useAuthStore((state) => state.session?.user); +export const useViewerStatus = () => useAuthStore((state) => state.status); ``` Never write to a store during server render (see b2c-b2b.md). +- `status` stays `'unknown'` on the server and in the first browser render, so auth-dependent parts render their skeleton until the browser knows the viewer, and `'unknown'` never reads as a guest. +- The `AppShell` calls the auth feature's `restoreSession` action once in an effect. It reads the session through the auth repository and calls `setSession` or `clearSession` ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). + ## Persisted store A store that survives a reload keeps its data in local storage through the `storage` adapter, so the key lands under the app's prefix (`shop.session.cart`). `stores/cart/cart-store.ts`: diff --git a/.claude/skills/front-end-architect/references/decisions.md b/.claude/skills/front-end-architect/references/decisions.md new file mode 100644 index 0000000..ec52ff1 --- /dev/null +++ b/.claude/skills/front-end-architect/references/decisions.md @@ -0,0 +1,81 @@ +# Decisions + +How to keep a project's architecture decision records (ADR) and design decision records (DDR) in one log, so a decision made once is followed in every later task. Read this file only when you add, accept, reject, or supersede a decision. To follow decisions, the index is enough ([SKILL.md](../SKILL.md)). + +Contents: Layout · When to record · Writing a record · Changing a decision · Precedence + +## Layout + +`docs/decisions/` at the monorepo root holds one file per decision and one index. Create both with the first decision. + +``` +docs/decisions/ + README.md # the index + 0001-zod-instead-of-valibot.md + 0002-island-components-over-native-elements.md +``` + +The index lists only live decisions, one line each. The line is the rule itself, one imperative sentence with its scope, so a task follows it without opening the record. Open a record only to change it, or when a case isn't clear from its line. + +```markdown +# Decisions + +## Design (DDR) +- 0002 Build UI with island components; never use native interactive elements (`button`, `input`, `select`, `textarea`, `a`) in features or apps. + +## Architecture (ADR) +- 0001 Validate with Zod instead of valibot in every project. + +## Proposed +- 0003 architecture: Load the reviews part only on interaction, on every product page. +``` + +- The area is where the rule applies: design for UI, island, tokens, copy, and UX; architecture for everything else. +- Keep a line under about 30 words. A rule that needs more is two decisions, or its detail belongs in the record. +- Rejected and superseded decisions leave the index. Their files stay, with their status, as history. + +## When to record + +- The user states a lasting rule for the project: "always", "never", "use X instead of Y", "from now on". Write it as `Accepted`, because the user decides, and say so in one line: "Recorded as decision 0004." +- You make a choice that is hard to undo, adds a dependency, deviates from this skill, or sets a pattern beyond the current task. Write it as `Proposed` and list it in the PR's plan. It binds nothing until the user accepts it. + +Don't record a one-off instruction for the current task, a rule this skill already states, or detail that one file shows. When you can't tell whether an instruction is lasting, follow it for the task and ask in your final message whether to record it. + +Before you propose a decision, search `docs/decisions/` for its topic, so you don't propose again what the user rejected or superseded. + +## Writing a record + +Number: the highest number in the folder plus 1, four digits. File name: `NNNN-.md`. Keep a record under about 25 lines. + +```markdown +# 0002 Island components over native elements + +Status: Accepted · Area: design · Date: 2026-10-04 · Decided by: user + +## Context +Why the decision came up, in one to three sentences. + +## Decision +The rule in the imperative, with its scope and exceptions. + +## Alternatives +- The option, and why it lost. "Not discussed" when the user gave none. + +## Consequences +What becomes easier or harder, and which existing code doesn't follow it yet. +``` + +- `Decided by` is `user` or `agent`. Add `Supersedes: NNNN` to the status line when it applies. +- Add the record's line to its area in the index, or to Proposed. +- Existing code that breaks a new decision is debt. List it under Consequences, and fix it only when the user asks or a task touches that code. + +## Changing a decision + +- Accept: set `Status: Accepted`, and move the line from Proposed to its area. +- Reject: set `Status: Rejected`, add the reason in one line under Decision, and remove the line from the index. +- Supersede: never rewrite the body of an accepted record. Write a new record with `Supersedes: NNNN`, set the old one to `Status: Superseded by MMMM`, and replace the old index line with the new one. A typo fix or clearer wording that keeps the rule is fine in place. +- When the user asks for something an accepted decision forbids, name the decision and ask: supersede it, or make a one-time exception. Record only a supersede. + +## Precedence + +An accepted decision overrides this skill's rules and your own judgment. A proposed decision overrides nothing. When a decision would break a rule that blocks a merge ([SKILL.md](../SKILL.md#7-review-stance)), such as tokens readable by JavaScript, state the risk once before you record it, and write the risk under Consequences. diff --git a/.claude/skills/front-end-architect/references/error-handling-code.md b/.claude/skills/front-end-architect/references/error-handling-code.md index fe06cee..3778504 100644 --- a/.claude/skills/front-end-architect/references/error-handling-code.md +++ b/.claude/skills/front-end-architect/references/error-handling-code.md @@ -121,9 +121,9 @@ export const PartBoundary = catchError(PartFallback); A part in a template: ```tsx - - }> - + + }> + ``` @@ -222,71 +222,59 @@ function makeQueryClient(): QueryClient { ```ts import 'server-only'; import { classifyError } from '@project/libs/error-handler'; -import { isHttpError } from '@project/libs/http'; -import { redirect } from 'next/navigation'; -import { ROUTES } from '../../navigation'; import type { ServerRead } from './types'; -export async function readOnServer( - read: () => Promise, - options: { returnTo?: string } = {}, -): Promise> { +export async function readOnServer(read: () => Promise): Promise> { try { return { status: 'ok', data: await read() }; } catch (error) { const outcome = classifyError(error).read; if (outcome === 'not-found' || outcome === 'no-access') return { status: outcome }; - if (options.returnTo && isHttpError(error) && error.status === 401) { - redirect(`${ROUTES.login}?redirect=${encodeURIComponent(options.returnTo)}`); - } throw error; } } ``` -`apps//src/app/(account)/orders/[id]/page.tsx`. `getOrder` is a cache, so the metadata and the page share one request, and the cache keeps a failure for the request too. +`apps//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. ```tsx import { StatusEmptyState } from '@project//app/error-boundaries'; -import { getDevice, getOrder, readOnServer } from '@project//server'; +import { getDevice, getSeller, readOnServer } from '@project//server'; import type { Metadata } from 'next'; import { notFound } from 'next/navigation'; -import { OrderDesktop } from './templates/order-desktop'; -import { OrderMobile } from './templates/order-mobile'; +import { SellerDesktop } from './templates/seller-desktop'; +import { SellerMobile } from './templates/seller-mobile'; -type OrderPageProps = { params: Promise<{ id: string }> }; +type SellerPageProps = { params: Promise<{ slug: string }> }; -export async function generateMetadata({ params }: OrderPageProps): Promise { - const { id } = await params; - const order = await readOnServer(() => getOrder(id)); - if (order.status !== 'ok') return { robots: { index: false } }; - return { title: order.data.title }; +export async function generateMetadata({ params }: SellerPageProps): Promise { + const { slug } = await params; + const seller = await readOnServer(() => getSeller(slug)); + if (seller.status !== 'ok') return { robots: { index: false } }; + return { title: seller.data.name }; } -export default async function OrderPage({ params }: OrderPageProps) { - const { id } = await params; - const [device, order] = await Promise.all([ - getDevice(), - readOnServer(() => getOrder(id), { returnTo: `/orders/${id}` }), - ]); - if (order.status === 'not-found') notFound(); - if (order.status === 'no-access') return ; - return device === 'mobile' ? : ; +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 ; + return device === 'mobile' ? : ; } ``` -A server part, `.../orders/[id]/organisms/order-invoice/OrderInvoice.tsx`: +A server part, `.../seller/[slug]/organisms/seller-ratings/SellerRatings.tsx`: ```tsx import { StatusEmptyState } from '@project//app/error-boundaries'; -import { getOrderInvoice, readOnServer } from '@project//server'; -import { InvoiceSummary } from './components/invoice-summary'; -import type { OrderInvoiceProps } from './types'; +import { getSellerRatings, readOnServer } from '@project//server'; +import { RatingsSummary } from './components/ratings-summary'; +import type { SellerRatingsProps } from './types'; -export async function OrderInvoice({ orderId }: OrderInvoiceProps) { - const invoice = await readOnServer(() => getOrderInvoice(orderId)); - if (invoice.status !== 'ok') return ; - return ; +export async function SellerRatings({ sellerId }: SellerRatingsProps) { + const ratings = await readOnServer(() => getSellerRatings(sellerId)); + if (ratings.status !== 'ok') return ; + return ; } ``` diff --git a/.claude/skills/front-end-architect/references/error-handling.md b/.claude/skills/front-end-architect/references/error-handling.md index e28444f..d3b49f0 100644 --- a/.claude/skills/front-end-architect/references/error-handling.md +++ b/.claude/skills/front-end-architect/references/error-handling.md @@ -108,7 +108,7 @@ 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, redirects a 401 to login with a return URL when the page passes `returnTo`, and rethrows the rest to the page's `error.tsx`. +- The page reads its main data through `readOnServer`, a server-only helper in the platform's `app/error-boundaries/`. It returns `{ status: 'ok', data }`, or `not-found` for 404 and 410 and `no-access` for 403, and rethrows the rest to the page's `error.tsx`. Server reads send no auth cookies, so only pages that are the same for every visitor read on the server; a page that needs a logged-in user loads in the browser ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). - `not-found` calls `notFound()`, which renders the group's `not-found.tsx`. When the page has already started streaming (it has a `loading.tsx`), the status stays 200 and Next.js adds a `noindex` robots tag, which search engines treat as not found. - `no-access` renders the page-size `StatusEmptyState`, and `generateMetadata` returns `robots: { index: false }` for it. `forbidden()` and `unauthorized()` are experimental and not used ([rendering-patterns.md](rendering-patterns.md#rendering-patterns)). - 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`. diff --git a/.claude/skills/front-end-architect/references/lib-error-handler.md b/.claude/skills/front-end-architect/references/lib-error-handler.md index b00d39f..2b9f50d 100644 --- a/.claude/skills/front-end-architect/references/lib-error-handler.md +++ b/.claude/skills/front-end-architect/references/lib-error-handler.md @@ -39,7 +39,7 @@ type ErrorWhere = 'app' | 'page' | 'part' | 'action' | 'refetch' | 'server'; interface ErrorContext { where: ErrorWhere; // where the error stopped - name?: string; // the part, action, or route, e.g. 'order-invoice'; never personal data + name?: string; // the part, action, or route, e.g. 'seller-ratings'; never personal data } interface ErrorReport extends Partial { @@ -90,7 +90,7 @@ The first matching row wins. | Not an `HttpError`, with a `digest` | network | boundary | toast | again | no | | Anything else | logic | boundary | toast | none | yes | -- 401 never reaches the UI: the HTTP lib refreshes, and a failed refresh logs out ([lib-http.md](lib-http.md#refresh-token)). The server has no refresh, so server code checks for 401 itself and redirects to login ([error-handling.md](error-handling.md#b2cb2b-server)). +- 401 never reaches the UI: the HTTP lib refreshes, and a failed refresh logs out ([lib-http.md](lib-http.md#refresh-token)). The server has no refresh and sends no auth cookies, so a server read never expects a 401; `readOnServer` rethrows one to its boundary like any other error ([error-handling.md](error-handling.md#b2cb2b-server)). - A `digest` without `HttpError` fields is a Server Component error seen in the browser: Next.js sends only the digest in production, so the browser can't classify it. The server already classified and reported it, and a retry renders the part again on the server. - Retry kinds: `again` offers a button that runs the same thing again; `wait` offers none and the hint says how long; `reload` offers a button that loads the latest data first; `fix` offers none, because the user must change the input; `none` offers none. diff --git a/.claude/skills/front-end-architect/references/lib-http.md b/.claude/skills/front-end-architect/references/lib-http.md index 3fd9f0f..fd3155a 100644 --- a/.claude/skills/front-end-architect/references/lib-http.md +++ b/.claude/skills/front-end-architect/references/lib-http.md @@ -175,11 +175,11 @@ A feature never sets `refresh`, `credentials`, or `getCookieHeader`: auth works - Single flight: one refresh at a time for the whole app, because the root and every feature client share one coordinator. Requests that get a 401 while a refresh runs wait for it. - Stale 401: each successful refresh increments a generation number. A request sent before the latest successful refresh that returns 401 is replayed right away, without another refresh. - On success, every waiting request is replayed once. A replay that gets 401 again fails with `UNAUTHORIZED` without refreshing again, so there are no loops. -- On failure, every waiting request fails with `UNAUTHORIZED` and `onFailure()` runs once (the app emits its logout event; the auth feature clears the store and redirects). Later requests try normally, so logging in again works without a reload. +- On failure, every waiting request fails with `UNAUTHORIZED` and `onFailure()` runs once (the app emits its logout event; the auth feature clears the store, and on a page that needs a logged-in user the `AuthGuard` sends the user to login). Later requests try normally, so logging in again works without a reload. - The refresh request is sent with `skipRefresh: true`, `retry: false`, and the normal timeout, and runs request interceptors like any request. - Waiting is abortable per request: an aborted waiter rejects with `ABORTED` while the refresh continues for the others. - In the browser, run the refresh inside `navigator.locks.request('http-refresh', ...)` when available, so two tabs never send the same refresh cookie at once (the back end may rotate and revoke it). -- On the server refresh is disabled. Server Components can't set cookies, so a 401 throws `UNAUTHORIZED`, and `proxy.ts` refreshes an expired session before rendering. +- On the server refresh is disabled. Server requests send no auth cookies (Server side), so the server render never reads or refreshes the session, and a 401 there throws `UNAUTHORIZED` to its boundary. ## Abort @@ -256,11 +256,27 @@ interface DownloadResult { ## Server side -- `bootstrap.server.ts` calls `configureServerHttp({ baseUrl: serverEnv.API_INTERNAL_URL, getCookieHeader: async () => (await cookies()).toString() })` once. 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 cookies too. 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, so each request forwards its own user's cookies. Never keep cookies, users, or tokens in module state. +- `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. - On the server, refresh is off, `abortAll` is unavailable, retry defaults to one attempt with a shorter timeout, `credentials` is ignored, and every request is sent with `cache: 'no-store'`, whatever `init` says. - `init` never carries Next.js caching options (`next: { revalidate, tags }`): the Next.js server keeps no cache between requests (see [b2c-b2b.md](b2c-b2b.md#no-server-cache)). +`bootstrap.server.ts`: + +```ts +configureServerHttp({ + baseUrl: serverEnv.API_INTERNAL_URL, + getCookieHeader: async () => + (await cookies()) + .getAll() + .filter(({ name }) => FORWARDED_COOKIES.has(name)) + .map(({ name, value }) => `${name}=${encodeURIComponent(value)}`) + .join('; '), +}); +``` + +`FORWARDED_COOKIES` is a `ReadonlySet` in the app's `constants/`, built from the cookie name constants ([lib-cookie.md](lib-cookie.md)). Adding an auth cookie to it is an override of rendering-patterns.md's Auth-dependent UI rule and needs a recorded decision. + ## Usage `features/catalog/http.ts`. `getEnv` is the owning project's env getter (see [lib-env.md](lib-env.md#project-env)). @@ -358,5 +374,5 @@ For building or changing the lib: [ ] Upload reports progress from 0 to 100, can be cancelled, and joins the refresh flow [ ] Download returns the blob and the file name from Content-Disposition [ ] Every failure is an HttpError with code, message, status, fieldErrors, hint, and requestId, plus retryAfter on a 429 or 503 that sends Retry-After; isHttpError works across bundles -[ ] On the server, each request forwards its own cookies, is sent with cache: 'no-store', refresh never runs, and no state leaks between requests +[ ] On the server, each request forwards only its own allowed cookies and never the auth cookies, is sent with cache: 'no-store', refresh never runs, and no state leaks between requests ``` diff --git a/.claude/skills/front-end-architect/references/page-example.md b/.claude/skills/front-end-architect/references/page-example.md index 14f647e..8724612 100644 --- a/.claude/skills/front-end-architect/references/page-example.md +++ b/.claude/skills/front-end-architect/references/page-example.md @@ -49,7 +49,7 @@ export { getProduct, getProductReviews, getRelatedProducts } from './features/ca export { getDevice } from './shared/utils/get-device'; ``` -`apps//src/app/(shop)/product/[id]/page.tsx`. `generateMetadata` and the page both call `getProduct(id)`, and the cache sends one request. A page whose main read can answer 404 or 403 reads through `readOnServer` instead, as the order page in [error-handling.md](error-handling-code.md) does. +`apps//src/app/(shop)/product/[id]/page.tsx`. `generateMetadata` and the page both call `getProduct(id)`, and the cache sends one request. A page whose main read can answer 404 or 403 reads through `readOnServer` instead, as the seller page in [error-handling-code.md](error-handling-code.md) does. ```tsx import { getDevice, getProduct } from '@project//server'; diff --git a/.claude/skills/front-end-architect/references/project-structure.md b/.claude/skills/front-end-architect/references/project-structure.md index 4d17857..4e20855 100644 --- a/.claude/skills/front-end-architect/references/project-structure.md +++ b/.claude/skills/front-end-architect/references/project-structure.md @@ -21,7 +21,7 @@ Three folders are named `tools`. Keep them apart: - Root `tools/`: scripts that run in a terminal, in CI, or through Nx (generators, validators). App code never imports them. TypeScript scripts run with jiti. - `packages/tools/`: shared runtime tools that apps and projects import. -- `packages/island/src/tools/`: design-system tools such as `cn`, `icon-sprite-plugin`, and `icon-name-extraction`. +- `packages/island/src/tools/`: design-system tools such as `cn`, `cvx`, `icon-sprite-plugin`, and `icon-name-extraction`. ## App (Next.js) @@ -49,7 +49,6 @@ apps//src/ │ └── templates/ # optional: this route's mobile and desktop templates ├── styles/ │ ├── app.css # Tailwind entry; imports island.css -│ ├── fonts.ts # next/font/local faces from island fonts/, set as CSS variables on │ └── index.ts ├── configs/ │ ├── seo.ts @@ -79,7 +78,7 @@ platforms//src/ │ │ ├── AppShell.tsx │ │ ├── types.ts │ │ └── index.ts -│ ├── guards/ # e.g. the route authentication guard +│ ├── guards/ # e.g. AuthGuard for pages that need a logged-in user │ │ └── / │ │ ├── .ts or .tsx │ │ └── index.ts @@ -191,7 +190,7 @@ packages/island/src/ ├── templates/ # like organisms ├── primitives/ # non-visual structural pieces, e.g. portal, error-boundary; like organisms ├── tools/ -│ └── / # e.g. cn, icon-sprite-plugin, icon-name-extraction +│ └── / # e.g. cn, cvx, icon-sprite-plugin, icon-name-extraction │ ├── .ts or .tsx │ ├── types.ts │ ├── constants.ts @@ -199,7 +198,8 @@ packages/island/src/ ├── styles/ │ ├── island.css # entry that apps import into their Tailwind v4 CSS │ ├── theme.css # primitive and semantic tokens -│ └── utilities.css # custom @utility definitions +│ ├── utilities.css # custom @utility definitions +│ └── fonts.css # @font-face rules for fonts/ ├── env/ # island's env: setEnv and getEnv, filled by the app's bootstrap │ ├── env.ts │ ├── types.ts @@ -207,7 +207,7 @@ packages/island/src/ ├── icons/ │ ├── symbol-defs.svg # sprite generated by Icomoon │ └── selection.json # Icomoon snapshot; re-import it into Icomoon to update the set -├── fonts/ # every app's fonts, e.g. yekan-bakh-vf.woff2; each app loads them with next/font/local +├── fonts/ # every app's fonts, e.g. yekan-bakh-vf.woff2 ├── constants.ts # island-level constants ├── index.ts └── server.ts diff --git a/.claude/skills/front-end-architect/references/refactoring.md b/.claude/skills/front-end-architect/references/refactoring.md index b7c832e..3275926 100644 --- a/.claude/skills/front-end-architect/references/refactoring.md +++ b/.claude/skills/front-end-architect/references/refactoring.md @@ -141,6 +141,9 @@ The catalog doesn't name these, but this stack has them. Each line gives the sme - `'use client'` on a page, layout, or template → only on the interactive leaf, driven by its part model ([b2c-b2b.md](b2c-b2b.md#rendering)). - Business logic in components → the model, action, mapper, or util that owns it ([SKILL.md](../SKILL.md#3-architecture-rules)). - Viewport checks choosing layouts → the template the server picks ([b2c-b2b.md](b2c-b2b.md#rendering)). +- A server render that depends on auth (a session read, auth cookies forwarded, a variant picked on the server, or a page that needs a logged-in user rendered on the server) → a browser part, or a page behind the `AuthGuard`, that renders its skeleton until the auth store knows the viewer ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). Leave it when the developer explicitly asked for it and the plan or a decision records it. +- The guest variant shown while the viewer is still unknown → the same-size skeleton while the auth store's `status` is `'unknown'` ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). +- A `` boundary or `'use client'` added to keep a part out of the server render → a technique from rendering-patterns.md's "What keeps a part out of the server HTML": browser-only state that renders the skeleton, `next/dynamic` with `ssr: false`, or `LoadOnVisible` ([rendering-patterns.md](rendering-patterns.md#choosing-where-a-part-loads)). - Cookie or storage reads during render → an effect or an event handler, or `cookies()` on the server passed down as a prop ([lib-cookie.md](lib-cookie.md#browser-only), [lib-local-storage.md](lib-local-storage.md#browser-only)). - Module-scope data on the server → React `cache()`, props, or the per-request `QueryClient` ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). - A page, loader, or server component that calls a repository directly → a cache, so every reader in the request shares one call ([b2c-b2b.md](b2c-b2b.md#data-flow)). diff --git a/.claude/skills/front-end-architect/references/rendering-patterns.md b/.claude/skills/front-end-architect/references/rendering-patterns.md index cd18c82..711bc52 100644 --- a/.claude/skills/front-end-architect/references/rendering-patterns.md +++ b/.claude/skills/front-end-architect/references/rendering-patterns.md @@ -2,16 +2,16 @@ 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 · Loading patterns · Choosing where a part loads +Contents: Rendering patterns · Auth-dependent UI · Loading patterns · Choosing where a part loads ## Rendering patterns -Apps render every page on the server for each request and stream it. +Apps render every page on the server for each request and stream it. The server render is the same for every visitor: what depends on the viewer renders in the browser (Auth-dependent UI below). | Pattern | Use | How here | |---|---|---| -| Client-side rendering | Parts only | A page renders only its browser-only parts in the browser ([b2c-b2b.md](b2c-b2b.md#data-flow)). | -| Server-side rendering | Always | Render every page fresh for each request, and read data through caches ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). | +| Client-side rendering | Auth-dependent pages and parts; other browser-only parts | A page or part whose UI depends on the viewer renders completely in the browser (Auth-dependent UI below). Other parts render in the browser only when [b2c-b2b.md](b2c-b2b.md#data-flow) says so. | +| Server-side rendering | Always, for what's the same for every visitor | Render every page fresh for each request, and read data through caches ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). The server render never depends on auth. | | Static rendering | Never | Nothing renders at build time. Keep each request cheap instead (first note below). | | Incremental static generation | Never | Nothing needs revalidating: after a mutation, `router.refresh()` renders the page again ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). | | Partial prerendering | Never | It needs Cache Components, which stay off. `loading.tsx` and `` give an early first paint instead ([b2c-b2b.md](b2c-b2b.md#rendering)). | @@ -27,6 +27,69 @@ Apps render every page on the server for each request and stream it. - 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. `` counts as stable from React 19.3 and Next.js 16.3 (View transitions row). [SKILL.md](../SKILL.md) prefers boring, proven technology. - Many patterns.dev examples use the Pages Router (`getServerSideProps`, `getStaticProps`, `next/head`), APIs removed in React 19, or libraries such as loadable-components and react-window. Take the idea and write the code with this stack's APIs. +## Auth-dependent UI + +The server render never depends on auth. Every visitor of a URL gets the same server HTML, whether they are a guest, a logged-in member, or a paying member. + +A page or part is auth-dependent when what it shows changes with who the viewer is: it needs a logged-in user (orders, addresses, settings), it shows a different UI per user type (a guest, a member without a subscription, a member with one), or it shows the viewer's own data (the cart count, a wishlist, recommendations, a member price). Locale, theme, device, and URL parameters aren't auth, so the server may render by them. + +- Same for every visitor → render it on the server, through "Choosing where a part loads" below. +- Depends on the viewer → render it completely in the browser. The server renders only its same-size skeleton: it never reads the session, sends auth cookies, or picks a variant. In the browser, the part's model reads the viewer and the viewer's data, and the part renders its variant. +- Render in the browser only the smallest piece that differs. A product page stays on the server and only its membership offer is a browser part. A page renders in the browser as a whole only when all of it depends on the viewer, such as an account page. +- Both are defaults. When the developer explicitly asks for a page or part to render on the server or in the browser, follow the request, state the trade-off, and write the override in the plan. When they make it a lasting rule, record it as a decision ([decisions.md](decisions.md#when-to-record)). Auth-dependent UI rendered on the server needs the auth cookies forwarded and the session refreshed in `proxy.ts` for the whole app, so record that override as a decision even for one page. + +Why: + +- The server renders the same thing for millions of mostly logged-out visitors, with no per-user back-end calls, so TTFB stays flat. +- The server can't refresh an expired session, because Server Components can't set cookies. A server render that read the session would show a member the guest UI, or fail, whenever the access token expired. In the browser, the HTTP lib refreshes and replays. +- One user's data can never reach another user's HTML through a misconfigured CDN or module state. +- Search engines crawl as guests, so they never saw auth-dependent UI. SEO loses nothing. + +How: + +- Server requests forward only the cookies the render needs, never the auth cookies ([b2c-b2b.md](b2c-b2b.md#state-and-auth)), so the back end can't personalize a server response by accident. +- The browser learns who the viewer is once per load. The `AppShell` calls the auth feature's `restoreSession` action in an effect, and the action moves the auth store's `status` from `'unknown'` to `'guest'` or `'member'` ([code-patterns.md](code-patterns.md#store)). The session endpoint answers a guest with an empty session, not 401, so a guest never starts a refresh or a logout. When the read still fails after the HTTP lib's retries, the action clears the session, so the status becomes `'guest'`, and rethrows; the `AppShell`'s effect passes the error to `handleError`. +- An auth-dependent part renders its same-size skeleton while the status is `'unknown'`. That covers the server render and the first browser render, so hydration matches. Never render the guest variant as the placeholder: a member would see it flash, and the layout would shift. +- When the part needs the viewer's own data, its model reads it with `useQuery`, enabled only when the status is `'member'`. Never use a server prefetch or `useSuspenseQuery` for it. +- Every variant ships in the route's bundle. Make a heavy variant, such as a subscriber's video player, a `next/dynamic` component with a same-size `loading` skeleton, so each visitor downloads only their own. +- A page that needs a logged-in user, such as every `(account)` page: the route group's layout wraps its children in the platform's `AuthGuard` (`app/guards/auth-guard/`). This client component renders the page skeleton while the status is `'unknown'`, sends a guest to login with a return URL, and renders the page for a member. The page stays a thin Server Component that resolves the device and passes only URL parameters to its template, and the template's parts load in the browser. `generateMetadata` reads no data: it returns a generic title and `robots: { index: false }`. +- An action that changes the viewer, such as login, logout, or a payment, updates the auth store, so every auth-dependent part renders its new variant. It doesn't call `router.refresh()`, because no server-rendered content changed. + +`platforms//src/features/membership/models/product/use-membership-offer-part.ts`. A guest sees an invitation to log in, a member without a subscription sees the subscription offer, and a subscriber (`user.hasSubscription`) sees their benefit. `types.ts` declares `MembershipOfferVariant = 'pending' | 'guest' | 'member' | 'subscriber'`. + +```ts +import { useCurrentUser, useViewerStatus } from '../../../../stores/auth'; +import type { MembershipOfferVariant } from './types'; + +export function useMembershipOfferPart(): MembershipOfferVariant { + const status = useViewerStatus(); + const user = useCurrentUser(); + if (status === 'unknown') return 'pending'; + if (status === 'guest') return 'guest'; + return user?.hasSubscription ? 'subscriber' : 'member'; +} +``` + +`apps//src/app/(shop)/product/[id]/organisms/membership-offer/MembershipOffer.tsx`. The product template, a Server Component, renders `` beside the server-rendered product summary. The server and the first browser render both show the skeleton. The part reads no data of its own, so it needs no `PartBoundary`; a variant that queries data gets one. + +```tsx +'use client'; + +import { useMembershipOfferPart } from '@project//features/membership'; +import { GuestOffer } from './components/guest-offer'; +import { MemberOffer } from './components/member-offer'; +import { MembershipOfferSkeleton } from './components/membership-offer-skeleton'; +import { SubscriberOffer } from './components/subscriber-offer'; + +export function MembershipOffer() { + const variant = useMembershipOfferPart(); + if (variant === 'pending') return ; + if (variant === 'guest') return ; + if (variant === 'member') return ; + return ; +} +``` + ## 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). @@ -144,9 +207,22 @@ export function ProductVideo({ video }: ProductVideoProps) { ## Choosing where a part loads -Ask about each part of a page in this order. Every match adds to the answer, so one part can use several steps: a product gallery renders its first image on the server (1), makes its thumbnails a small client leaf (2), and loads its zoom viewer only when the user opens it (3 and 4). 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). -1. Search engines or the first paint need it → a Server Component that reads caches, inside `` with a same-size skeleton when it's slow. -2. 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. -3. It's personal, 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). -4. 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`. +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 `` 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`. + +**What keeps a part out of the server HTML.** `'use client'` doesn't, and neither does ``. Client components render to HTML on the server and then hydrate. `` 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: + +| 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) | +| `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 `` for streaming and selective hydration, never to move a part to the browser.