chore: nx init

This commit is contained in:
Amiram_se 2026-10-02 17:46:30 +04:00
parent a4f5a94137
commit 8cb189ed39
20 changed files with 3700 additions and 0 deletions

31
.claude/settings.json Normal file
View File

@ -0,0 +1,31 @@
{
"extraKnownMarketplaces": {
"nx-claude-plugins": {
"source": {
"source": "github",
"repo": "nrwl/nx-ai-agents-config"
}
}
},
"enabledPlugins": {
"nx@nx-claude-plugins": true
},
"sandbox": {
"filesystem": {
"allowRead": [
"/tmp/.nx",
"~/.nx"
],
"allowWrite": [
"/tmp/.nx",
"~/.nx"
]
},
"network": {
"allowUnixSockets": [
"/tmp/.nx",
"~/.nx"
]
}
}
}

View File

@ -0,0 +1,217 @@
---
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) or admin panels (React, TanStack Router, access levels, multi-domain endpoints, in-app help). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and token refresh; env validation; 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, sonner, and Playwright, using Spec Kit. Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, screens, components, features, or Nx projects in these monorepos, when planning a feature with Spec Kit, or when another skill such as a product designer or architect needs front-end input.
---
# Front-end Architect
Act as a principal front-end architect for Nx monorepos that ship B2C/B2B websites or admin panels. You design, scaffold, implement, and review front-end code so it stays fast, maintainable, and consistent across projects.
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.
- Prefer boring, proven technology, fewer re-renders, and the user's time.
## 1. Identify the project type
| | B2C/B2B | Admin panel |
|---|---|---|
| Who uses it | The public, 1–20 million visitors a day (Amazon, eBay, Digikala) | Staff who manage a B2C/B2B site from a back office |
| App | Next.js App Router, routes in `apps/<app>/src/app/` | React + TanStack Router, code-based route tree in `navigation/navigation.ts`, screens in `src/screen/` |
| Business logic | `platforms/<app>/` (the app stays thin) | Inside the app (`apps/<app>/src/features/`) |
| Server entry | Every project except apps has `src/server.ts` | None |
| Critical | A fresh server render per request with no server cache, web vitals, bundle and chunk size, hydration and navigation speed | Access levels, multiple business domains and endpoints, in-app help, operator UX |
Read the matching playbook before designing or writing code:
- B2C/B2B: [references/b2c-b2b.md](references/b2c-b2b.md)
- Admin panel: [references/admin-panels.md](references/admin-panels.md)
One monorepo can hold both, for example a site and its back office. Apply each playbook to its own apps. A shared package follows the B2C/B2B rules (including `server.ts`) when any B2C/B2B app uses it.
## 2. Stack
| Concern | Tool | Rule |
|---|---|---|
| Monorepo | Nx | Scaffold with generators (local ones in `tools/` when the repo has them) so every component, feature, and repository has the same shape |
| B2C/B2B app | Next.js App Router | Server Components by default |
| Admin app | React + TanStack Router | Code-based routes; every screen lazy-loaded |
| Styling | Tailwind CSS v4 | Tokens live in island `styles/theme.css`; no raw colors or sizes where a token exists |
| Variants | class-variance-authority, clsx, tailwind-merge | cva in each component's `variants.ts`; merge classes with island's `cn` tool |
| Validation | valibot | Forms, env, and untrusted input. Not Zod |
| Forms | react-hook-form + @hookform/resolvers | `valibotResolver` with schemas from `shared/validations/` |
| Client state | zustand + immer | One store per feature or domain; components subscribe through selectors |
| Server state | TanStack Query | Configured in `configs/react-query.ts`; query keys live in the repository's `constants.ts`; queries don't retry, because the HTTP lib does |
| Toasts | sonner | After every completed action |
| i18n | i18next + react-i18next | No hard-coded UI text |
| Env | @t3-oss/env-core + valibot | The app validates its variables with `createClientEnv` and `createServerEnv` from `packages/libs/env`; other projects read only their own `env/` |
| Lint and format | oxlint, prettier | ESLint runs module-boundary rules only |
| TS scripts and configs | jiti | Runs `tools/` scripts and TypeScript config files without a build step |
| Icons | svgo | Through island's `icon-sprite-plugin` |
| E2E | Playwright | Every feature, plus screenshot inspection |
| Spec-driven development | Spec Kit | See section 4 |
TanStack Query is implied by `configs/react-query.ts`; confirm the repo uses it before adding it. Don't add any dependency outside this stack without stating why and getting approval.
## 3. Architecture rules (both types)
Full trees with folder descriptions, Nx tags, the env flow, and export mechanics: [references/project-structure.md](references/project-structure.md). Code for every layer: [references/code-patterns.md](references/code-patterns.md).
Shared libs have full specs. Read the matching one before building or changing the lib, or writing code that sends requests, adds or reads env, reads or writes cookies, or persists data on the device:
- HTTP client: [references/lib-http.md](references/lib-http.md)
- Env: [references/lib-env.md](references/lib-env.md)
- Cookies: [references/lib-cookie.md](references/lib-cookie.md)
- Local storage: [references/lib-local-storage.md](references/lib-local-storage.md)
Patterns and refactoring have their own references. Read each one only when its trigger applies:
- 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, decided per project type, before you add or move a part of a page or change 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**
- Files and directories are kebab-case. Component files are PascalCase (`Button.tsx`, `AppShell.tsx`, `AuthGuard.tsx`). Hooks are `use-hook-name.ts`.
- Entry files with fixed names keep them: Next.js `page.tsx`, `layout.tsx`, `loading.tsx`, and admin `screen/**/page.tsx`. Route groups are kebab-case too: `(auth)`.
**Projects and exports**
- Every project keeps its code under `src/`.
- Every module has an `index.ts` that re-exports its public API by name: `export { Button } from './Button';` and `export type { ButtonProps } from './types';`. Never `export *`.
- Exports are tree-shakeable. Each module is importable from the project root and from its own subpath: `import { Button } from '@project/island'` or `import { Button } from '@project/island/atoms/button'`. B2C/B2B code always imports by subpath.
- B2C/B2B: every project except apps has `src/server.ts` beside `src/index.ts`. It starts with `import 'server-only';`, is exposed as the `/server` subpath, and holds server-only capabilities. `index.ts` never imports from `server.ts`.
- A module with server-only capabilities has its own `server.ts` beside its `index.ts` (the env lib), and a server-only module has only `server.ts` (a feature's `caches/`). Both start with `import 'server-only';`, and the project's `server.ts` re-exports them by name.
**Dependency direction**
- apps → platforms (B2C/B2B only) → packages. Nothing imports upward, and one product's app or platform never imports another's. ESLint enforces this through Nx tags.
- island follows atomic design: atoms → molecules → organisms → templates, and a level never imports a level above it. `primitives/` are non-visual structural pieces (for example a portal) outside that ladder. The `components/` and `hooks/` inside an organism are private to it, except a compound component's named parts, which its `index.ts` re-exports.
**Features are DDD** (`features/<feature>/`)
- `entities/`: back-end data model types, enums, and unions. Types only.
- `http.ts`: the feature's HTTP client, `export const catalogHttp = http.extend({ ... })`. Only the feature's repositories import it, and its `index.ts` doesn't export it. It may set the base URL, headers, timeout, retry, and feature-only interceptors, never refresh or cookie settings. A feature with nothing special still has `http.extend({})`.
- `repositories/`: make the request through the feature's HTTP client and return the data. They never use client-side dependencies (hooks, stores, `window`, `cookie`, `storage`), so they also run on the server. Each endpoint has four types: `*Args` (caller input), `*Dto` (request body), `*ResponseDto` (raw response), and `*Payload` (the shape apps and stores use). `mappers.ts` turns `*Args` into `*Dto` and `*ResponseDto` into `*Payload`. No `*Dto` leaves the repository.
- `caches/` (B2C/B2B platforms only, server-only): React `cache()` wrappers around repository calls, so each distinct call runs once per request however many server components need it. Its entry is `server.ts`, not `index.ts`.
- `actions/`: one operation from start to end. The login action sends the request, checks the response, updates the store and local storage, makes any follow-up calls, emits `auth.login`, and returns `'ok'`. Use an action whenever an operation has side effects beyond the request. Every action emits its event through the event emitter when its steps succeed, unless the caller passes `{ emit: false }`, so other features and integrations react to it without the action knowing them.
- `models/`: page and part logic as hooks. A page has one page model (`models/login/use-login-page.ts`), or a page model plus one model per part when its parts load or change on their own (`use-shipment-page.ts`, `use-shipment-address-part.ts`, `use-shipment-bill-part.ts`). Pages, screens, templates, and parts get their data and handlers from their model and stay presentational.
- `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 `<feature>-validations.ts` per feature).
**Data flow**
- Client side (admin panels, and the parts of a B2C/B2B page that load in the browser): repository → model → UI. Every page has a skeleton (`loading.tsx`, or the admin route's `pendingComponent`). Every part that loads on its own has its own `<Suspense>` with a same-size skeleton and its own error boundary, so one slow or failing part never blocks the others.
- Server side (B2C/B2B only): repository → cache → server components. Pages, `generateMetadata`, and server components read data only through caches. A client component gets server data as props, or through React Query hydration when it must stay live. Details: [references/b2c-b2b.md](references/b2c-b2b.md#data-flow).
**Env, HTTP, cookies, and storage**
- Env (`packages/libs/src/env`): the app declares its variables in its `env/` and validates them with `createClientEnv` (public variables, both sides) and `createServerEnv` (server variables, server only). Those files are the only code that reads `process.env` or `import.meta.env`. Every other project that reads env has `src/env/` with `setEnv` and `getEnv` for its own values, 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.
- 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 }`.
- Cookies (`packages/libs/cookie`, the `cookie` instance): only small values the server needs on the request, such as locale and theme. Never tokens: auth cookies are HttpOnly and belong to the server. Browser only; server code reads cookies with `next/headers`.
- Local storage (`packages/libs/local-storage`, the `storage` instance): client-only, non-critical data under the app's key prefix, and the storage behind persisted zustand stores. Never tokens or personal data.
- `cookie` and `storage` are never read during render, at module top level, or in repositories.
**Design system (island)**
- Build UI from island. Never fork or restyle an island component inside a feature; add a variant to island and use it.
- Components use semantic tokens (`--color-surface-card`, `--color-text-muted`, `--color-action-primary`) layered over primitive tokens in `theme.css`. That layering is what makes theming and dark mode possible without a rewrite.
- Every component defines its variants, sizes, and states (default, hover, focus-visible, active, disabled, loading, error, selected) and its accessibility behavior. Enabled interactive elements show `cursor: pointer` and disabled ones `cursor: not-allowed`, built into the component so no screen can forget them.
- Complex organisms are compound components (`<DataTable>`, `<DataTable.Toolbar>`, `<DataTable.Pagination>`) that share state through context, with slots or render props for the parts that vary per entity, such as cells, empty states, and toolbars.
**Cross-cutting**
- Separate concerns: components render, models orchestrate, actions run operations, repositories talk to the network through their feature's HTTP client, and caches share server reads within a request. No `fetch` outside the HTTP lib.
- Keep one source of truth per kind of state: server state in the query cache, URL state in the URL, form state in react-hook-form, shared client state in zustand, and ephemeral UI state in the component. Never copy one into another.
- Keep the UI stable: colocate state, split large contexts, never let an update unmount and remount a visible subtree, and never use random values or array indexes as keys for dynamic lists.
- Model multi-step flows (wizards, imports, bulk actions) as explicit states, such as `idle → validating → uploading → processing → done | failed`, never as a set of booleans.
- Wrap every route and every independent widget in an error boundary, so one broken widget never takes down the page.
- Every text comes from i18next and is a simple, complete description of its purpose ("Save changes to this category", not "Save"). Support RTL and LTR: set `lang` and `dir` from the locale, and use logical utilities (`ms-*`, `pe-*`, `start-*`) instead of left and right.
- Meet WCAG 2.1 AA: 4.5:1 text contrast, visible focus rings, full keyboard operation, and an `aria-label` on every icon-only button.
## 4. Workflow
Projects use Spec Kit for spec-driven development. For a new feature, follow its flow and supply the architecture at each step, as described in [references/spec-kit.md](references/spec-kit.md):
`/speckit-constitution` (once per repo) → `/speckit-specify` → `/speckit-clarify` → `/speckit-plan` → `/speckit-checklist` → `/speckit-tasks` → `/speckit-analyze` → `/speckit-implement` → `/speckit-converge`
`clarify`, `checklist`, and `analyze` are optional quality gates; use them for production features.
For any design or implementation task, with or without Spec Kit:
1. **Clarify the job.** Who uses it, how often, and what they finish with it. State assumptions.
2. **Identify the project type** and read its playbook.
3. **Map the data.** Entities, repository types (`*Args`, `*Dto`, `*ResponseDto`, `*Payload`), caches and how each client part gets its server data (B2C/B2B), 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)).
5. **Design every state first:** loading, empty, error, in progress, then populated.
6. **Build with island components**, adding variants to island when needed.
7. **Wire feedback:** a toast for every completed action, errors mapped to fields, form alerts, or toasts, and progress for long operations.
8. **Check performance:** bundle, hydration, and web vitals (B2C/B2B); re-renders and flicker (admin).
9. **Test with Playwright:** happy path, validation error, and server error. Take screenshots at every target viewport, inspect them, fix what you find, and repeat until clean.
10. **Verify and deliver.** Run lint, type-check, and tests for the affected projects through Nx (`nx affected -t <targets>`; check target names with `nx show project <name>`). Finish with the Definition of Done and a short note on trade-offs, including each new non-obvious pattern with its signal and the simpler option you rejected, and the smells you noticed but left as debt.
## 5. Collaborating with other skills
Before deciding alone on something outside front-end architecture, check the available skills. When one matches, read its `SKILL.md` and let it lead in its area:
| Area | Skills like | They own | You own |
|---|---|---|---|
| Product and UX design | product-designer, ux, ui-design | User flows, layouts, visual hierarchy, token values | Mapping the design onto island, states, feasibility, performance cost |
| System or back-end architecture | architect, solution-architect, backend | Service boundaries, API contracts, auth flows | DTO mapping, and the pagination, filter, and error contracts the UI needs |
| Figma | figma-design-to-code and other figma-* skills | Reading the design | Adapting it to island components and tokens |
| Nx | nx-workspace, nx-generate, nx-run-tasks | Generators, project graph, running targets | Which project and tags new code gets |
| Spec Kit | speckit-* | The process and its artifacts | The architecture content inside them |
| Review, security, QA | Review, security, and testing skills | Their checks | The rules in this skill |
When you hand off, send a short brief: the context, the decision you need, and the constraints from this skill (stack, structure, budgets). When another skill asks for front-end input, reply with a front-end brief: project type, affected projects and folders, data flow (repository → action → model → UI), required states, performance or access concerns, and open questions.
If no matching skill is available, make the call yourself and label it as an assumption.
## 6. Definition of Done
Copy this into the PR description, add the list from the project type's playbook, and tick every item.
```
Structure
[ ] Code is in the right project and folder, under src/, named per the naming rules
[ ] Public API is exported by name from index.ts (and server.ts for B2C/B2B); no export *
[ ] ESLint boundaries pass; no upward or cross-product imports
[ ] Repositories have no client-side dependencies; UI and stores use *Payload types only
[ ] Repositories send requests only through their feature's http.ts client; no fetch outside the HTTP lib
[ ] Env is read only in the app's env/ files and through each project's getEnv(); no process.env or import.meta.env elsewhere
[ ] 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 plan or PR
[ ] Refactors are in their own commits, and the PR states how unchanged behavior was checked; smells noticed but not fixed are listed as debt
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 error boundary
[ ] Every completed action shows a toast; every error says what happened and how to fix it
[ ] Query cache is updated or invalidated after every mutation; no stale data is visible
[ ] Refetches never swap content for a spinner; keys are stable
Quality
[ ] All UI text comes from i18next; RTL and LTR both render correctly
[ ] AA contrast, focus-visible rings, keyboard operation
[ ] oxlint, prettier, ESLint boundaries, type-check, and Playwright pass for affected projects
[ ] Playwright covers happy path, validation error, and server error; screenshots inspected at every target viewport
```
## 7. Review stance
Every review comment names the rule, shows the problem, and proposes the fix. For example:
> **Repositories stay server-safe:** `products.ts` reads the page size with `storage.getItem`, which breaks server rendering. Pass `pageSize` in `ListProductsArgs` and read the stored value in an effect of the `use-products-page` model.
Name a code smell and its technique, with the target layer or file, as [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; missing Playwright coverage; inaccessible contrast; UI that flickers on update; a page, action, or navigation item without its permission check (admin); or, for B2C/B2B, 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.

View File

@ -0,0 +1,320 @@
# Admin panel playbook
Back-office panels where staff manage a B2C/B2B site, often eight hours a day, repeating the same task hundreds of times. Treat them as production software, not throwaway CRUD screens: every screen should let operators finish faster, with fewer mistakes and less fatigue than a spreadsheet. UX is the primary deliverable.
Contents: Access levels · Business domains and endpoints · Help system · Screens and routing · UX rules (copy, data and cache, file uploads, surfaces and color, cursors, feedback, stability, responsiveness, loading and progress, lists, errors, lazy loading, forms, keyboard, performance) · Example: route, guard, and screen · Testing · Definition of Done
## Access levels
Pages, actions, and sidebar items are all permission-aware. The back end is the authority; front-end checks are UX, never security.
- Permissions arrive with the session (the login action fetches them) and live in the auth store. They are a typed union in `features/access/entities/permission/types.ts`, for example `'catalog.products.read' | 'catalog.products.update'`.
- Pages: every route in `navigation/navigation.ts` runs a guard in `beforeLoad`. Signed-out users go to login with a return URL. Users without the permission go to a "no access" screen that explains why and links back. Never render a blank page.
- Actions: wrap buttons and menu items in `PermissionGuard`, or use `useHasPermission`. Hide actions the role can never use. When the role has the action but it's unavailable right now (for example, the order is locked), disable it with a tooltip that says why.
- Sidebar: each item in `navigation/constants.ts` carries its permission, a navigation hook filters the items, and a group with no visible items disappears.
- A 403 from the API means permissions changed mid-session. Tell the user what they tried and why it failed, then refresh the permissions.
## Business domains and endpoints
- One DDD feature per business domain: catalog, orders, customers, finance. A domain may call its own service or base URL. Set it in the feature's `http.ts` from the app's env, `export const catalogHttp = http.extend({ baseUrl: () => clientEnv.VITE_CATALOG_API_URL })`, so every domain shares the root client's auth refresh, interceptors, and error normalization, and only one refresh runs at a time across domains. A domain may also set its own headers, timeout, and retry there, never auth settings (see [lib-http.md](lib-http.md#root-and-feature-clients)).
- Each domain's mappers convert that service's DTO conventions to `*Payload`, and every domain surfaces the same normalized error shape.
- Query keys start with the domain (`['catalog', 'products', ...]`) so invalidation stays precise.
- Features import other features only through their `index.ts`. A screen that spans domains composes several models; features don't reach into each other.
## Help system
Operators should never have to guess what a page, action, or flow does.
- Every screen shows a one-sentence description under its title: what the page is for and when changes take effect.
- Every action with non-obvious consequences (bulk operations, imports, status transitions, permission changes, anything irreversible or asynchronous) has an info icon beside it. The help says what the flow does, what it affects, how long it takes, and what happens if it fails. Example: "Publishing this catalog makes all 340 active products visible on the storefront within about 2 minutes. Products missing a price will be skipped and listed in a report."
- Business flows with states, such as the order lifecycle or refund approval, get a help panel that describes each state and the allowed transitions.
- Fields that need explanation get help text under the field.
- Help text lives in i18n resources under a `help` namespace, keyed by screen, action, or flow ID, so it is translatable and reviewable. The info-icon popover and the help panel are island components. A script in `tools/` can check that every route and flagged action has a help entry.
## Screens and routing
- Routes are code-based in `navigation/navigation.ts`. Each route runs its guard in `beforeLoad`, validates its search params with a valibot schema in `validateSearch`, and lazy-loads its screen with `lazyRouteComponent`, using a skeleton of the page layout as `pendingComponent`.
- `screen/<page-name>/page.tsx` is a thin entry: it calls the page's model hook and renders the template. Each screen level may keep its own `organisms/` and `templates/`.
- A part that loads or changes on its own (a filters panel, a stats card, a table) calls its own part model and sits in its own `<Suspense>` with a same-size skeleton and its own error boundary. What the parts share, such as the selected row or the current step, lives in the page model and reaches the parts as props.
- The shell (sidebar, header, breadcrumbs) stays mounted across navigation; only the outlet changes.
Every screen has the same anatomy, so operators never hunt for navigation:
1. A title that names the page and its object ("Edit Category", "Product: Blue Ceramic Mug"), matched by the document title ("Edit Category · Admin").
2. Breadcrumbs with every ancestor linked: Dashboard / Catalog / Categories / Edit Category.
3. A back button ("Back to Categories") that goes to the logical parent, not `history.back()`, so it also works from a direct link.
4. Primary actions in the header on desktop and in a sticky bottom bar on mobile.
5. Info icons for complex actions and flows.
```tsx
<PageHeader
breadcrumbs={[
{ label: t('nav:dashboard'), to: '/' },
{ label: t('nav:catalog'), to: '/catalog' },
{ label: t('nav:categories'), to: '/catalog/categories' },
{ label: t('category.edit.title') },
]}
backTo={{ label: t('category.edit.back'), to: '/catalog/categories' }}
title={t('category.edit.title')}
description={t('category.edit.description')}
actions={
<Button type="submit" form="category-form">
{t('category.edit.save')}
</Button>
}
/>
```
## UX rules
### Copy
- Every label, button, tooltip, and message is a simple, complete description of its purpose. Buttons name the action and its object ("Delete this category", not "Delete"). Headings describe their content. Tooltips describe the outcome, not the control.
- Error messages have three parts: what went wrong, why (if known), and what the user can do. "The file could not be uploaded because it is larger than 10 MB. Compress the image or choose a smaller file, then try again."
- Empty states say what would normally be here, why it is empty, and the next step, with a primary action when there is one: "No categories yet. Create your first category to start organizing products." plus a "Create category" button.
### Data and cache
- After every create, update, or delete, update or invalidate every query that can contain the entity (code in code-patterns.md). Users never see stale data right after changing it.
- Paginated tables use `placeholderData: keepPreviousData`, so the current page stays visible while the next one loads.
- Prefetch the next page when the pointer rests on "Next page", and prefetch detail data on row hover when latency matters.
### File uploads
- Every upload shows a progress bar with a numeric percentage ("Uploading… 63%"), the file name and size, a cancel button while uploading, and a clear success or failure state with a retry action. Multiple files show per-file progress and an overall bar. Uploads go through the feature client's `upload()`: its `onProgress` drives the bar, and the cancel button aborts the `signal`. Uploads never retry automatically; the retry action sends the file again (see [lib-http.md](lib-http.md#files)).
### Surfaces, color, and contrast
The interface is never just black and white. Define these as semantic tokens in island `theme.css`:
- Page background: a soft tinted neutral (for example `#F4F6FA` light, `#0F1319` dark), never pure white or pure black.
- Navbar and sidebar: a surface distinct from the page (darker or brand-tinted), so navigation separates at a glance.
- Cards and panels: lighter than the page (`#FFFFFF` light, `#161B23` dark), with a subtle 1 px border at about 8–12% contrast and a soft shadow (`0 1px 2px rgba(16,24,40,.06), 0 1px 3px rgba(16,24,40,.10)`).
- Sections inside cards: separated by dividers, spacing steps, or a faint tint on headers and footers.
- Status colors (success, warning, danger, info), each with fill and text variants that meet contrast on their background.
- The accent color is reserved for primary actions and active navigation.
- Text meets WCAG 2.1 AA: 4.5:1 for body text, 3:1 for large text and UI boundaries. Check it with axe in Playwright and by inspecting screenshots.
- Interactive states are visible: hover, focus-visible (2 px ring in the accent color), active, selected, and disabled (reduced opacity plus `cursor: not-allowed`).
### Cursors and affordances
- Every enabled button, link, clickable row, sortable header, tab, and chip shows `cursor: pointer`. Build it into the island components.
- Every clickable element looks different from static text. Sortable headers show a sort icon (neutral when unsorted, filled and accent-colored with a direction arrow when sorted) and change background on hover. Clickable rows highlight on hover. Links are underlined or colored. Icon-only buttons have a tooltip and an `aria-label`. A column header is never plain text with no indicator.
### Feedback
- Every completed action shows a toast that says exactly what was done, naming the object when possible: "Category 'Kitchenware' was deleted", "3 orders were marked as shipped". Success toasts auto-dismiss after 4–6 s. Error toasts stay until dismissed and include the fix and, when possible, a retry: `toast.error(message, { description: hint, duration: Infinity, action: { label, onClick: retry } })`.
- When the user changes a table page, scroll to the top of the table, not necessarily the window: a ref on the table container and `scrollIntoView({ block: 'start', behavior })`, with `behavior: 'auto'` under `prefers-reduced-motion`.
- Destructive actions ask for confirmation, naming the object and the consequence: "Delete category 'Kitchenware'? Its 12 products will become uncategorized. This cannot be undone."
- Prefer reversible designs: soft deletes, and "Undo" in the toast when the back end supports it.
### Stability
Refetches, state updates, and re-renders must never make the UI disappear and reappear.
- Never switch between `isLoading ? <Spinner /> : <Table />` on refetch. Keep showing the data with a subtle inline indicator driven by `isFetching`.
- Keep layout containers mounted and swap only their contents.
- Use skeletons with the final content's dimensions, and reserve space for images and charts with fixed aspect ratios.
- Put a `Suspense` boundary at the page level with a skeleton of the page layout, so the shell never flickers during route transitions.
- A part whose model uses `useSuspenseQuery` changes its query key inside `startTransition`, so a page or filter change keeps the current content instead of falling back to the skeleton.
### Responsiveness
Design and verify every screen at three viewports, with the breakpoints defined in island `theme.css` (`--breakpoint-tablet: 64rem`, `--breakpoint-desktop: 90rem`, which give the `tablet:` and `desktop:` variants):
- Desktop, 1440 px and wider: full sidebar, multi-column forms, dense tables with all columns.
- Tablet, 1024–1439 px: icon-only collapsible sidebar, two-column forms, low-priority columns behind a "More" column or a row expander.
- Mobile, 0–1023 px: sidebar in a drawer, single-column forms, tables as card lists or horizontal scroll with a sticky first column, and a sticky bottom action bar for primary form actions. Touch targets are at least 44×44 px.
### Loading, progress, and empty states
- Design the loading and empty states together with the populated state. Loading states are skeletons that match the final layout. Empty states have an icon or illustration, one sentence, and a primary action when there is one.
- Anything that takes more than about 2 seconds, or has server-side steps, shows a progress bar, a numeric percentage, and the current step: "Importing products… 42% — Validating row 1,200 of 2,850." When progress is unknown, show an indeterminate bar with step labels and elapsed time. Never show a bare spinner for more than 3 seconds. Allow cancelling when the back end supports it, and say whether leaving the page interrupts the process.
- The clicked button shows a spinner, becomes disabled, and changes its label to the in-progress form ("Saving…"). The rest of the form stays visible and read-only.
### Lists and pagination
- Long lists are paginated on the server, with page sizes 10, 25, 50, and 100. Page, size, sort, and filters live in the URL (`?page=3&pageSize=50&sort=-createdAt`), so views are shareable and survive a refresh.
- The pager shows "Showing 51–100 of 1,284". Management tables never use infinite scroll; only feeds do.
- Row selection offers "select all on this page" and, when meaningful, "select all 1,284 matching items" with an explicit confirmation.
### Errors
- Show every API or action error in the right place: validation errors under their fields, errors about the whole submission in a form-level alert, background or non-form action errors in a toast, and a failed page load as a full-page error with a retry button.
- Map known server codes to actionable messages. Unknown errors say: "Something went wrong on our side. Try again in a moment. If it keeps happening, contact support and mention reference ID `a1b2c3`." Include the request ID whenever the server returns one.
- Errors never blank out the page; the shell, breadcrumbs, and back button stay usable.
- Report unexpected errors, with their request ID, to the error-tracking integration (for example Sentry).
### Lazy loading
Load everything lazily that can be: routes, heavy widgets (charts, editors, PDF viewers, maps) with skeleton fallbacks, images with `loading="lazy"` and explicit dimensions, select and autocomplete options (fetched on open, searched and paginated on the server), tab content on first activation, and modal content when the modal opens.
### Forms
- Validate on the client with valibot before submitting, and show errors inline under the field in plain language that says how to fix them ("Enter a price greater than 0. Use a dot as the decimal separator."). Validate on blur first, then on change (`mode: 'onTouched'`).
- Put server errors in the right place (code in code-patterns.md) and scroll to and focus the first invalid field.
- Disable the submit button only while submitting, never because the form is invalid; users need to click it to find out what's wrong.
- Warn before leaving a form with unsaved changes (TanStack Router `useBlocker`). Show the dirty state and offer "Discard changes" next to the primary action when the form is dirty.
### Keyboard and context
- Tab order follows reading order, Enter submits, and Esc closes. Set sensible default focus, keep primary actions in consistent places, skip confirmations for safe actions, and add shortcuts for the most common operations.
- Reduce cognitive load: group related fields, use progressive disclosure for advanced options, and prefer sensible defaults over required choices.
- Preserve context: filters, sort, page, and scroll position survive navigating to a detail page and back.
- Respect `prefers-reduced-motion` and `prefers-color-scheme`.
### Performance
- Split code by route (every screen is lazy) and by heavy widget.
- Paginate on the server; a table page stops at 100 rows. When a list still renders more than about 200 rows, such as a feed, a log, or a large tree, try `content-visibility` first; a virtualization library is outside the stack and needs approval ([rendering-patterns.md](rendering-patterns.md)).
- Colocate state, split large contexts (`FiltersContext` and `SelectionContext`, not one `TableContext`), and subscribe to store slices with selectors.
- Memoize table rows and give them stable, primitive props; wrap callbacks and expensive derived data passed to memoized children in `useCallback` and `useMemo`. If the repo enables the React Compiler, skip manual memoization and check the result in the Profiler.
- Debounce search inputs by 250–400 ms.
- Profile before optimizing: fix the top three offenders, then measure again.
- Budgets: shell JS at most 200 KB gzipped, route chunks at most 100 KB, and LCP under 2.5 s on a mid-range laptop over a throttled connection.
## Example: route, guard, and screen
`apps/<app>/src/guards/require-permission/require-permission.ts`
```ts
import { redirect } from '@tanstack/react-router';
import type { Permission } from '../../features/access';
import { ROUTES } from '../../navigation/constants';
import { useAuthStore } from '../../stores/auth';
export function requirePermission(permission: Permission, returnTo: string): void {
const { session } = useAuthStore.getState();
if (!session) {
throw redirect({ to: ROUTES.login, search: { redirect: returnTo } });
}
if (!session.permissions.includes(permission)) {
throw redirect({ to: ROUTES.noAccess });
}
}
```
`apps/<app>/src/guards/permission-guard/PermissionGuard.tsx`
```tsx
import type { ReactNode } from 'react';
import type { Permission } from '../../features/access';
import { useHasPermission } from '../../stores/auth';
type PermissionGuardProps = { permission: Permission; children: ReactNode; fallback?: ReactNode };
export function PermissionGuard({ permission, children, fallback = null }: PermissionGuardProps) {
return useHasPermission(permission) ? children : fallback;
}
```
`apps/<app>/src/navigation/navigation.ts`
```ts
import { createRootRoute, createRoute, createRouter, lazyRouteComponent } from '@tanstack/react-router';
import { requirePermission } from '../guards/require-permission';
import { productListSearchSchema } from '../shared/validations';
import { ListPageSkeleton } from './components/list-page-skeleton';
import { RootLayout } from './components/root-layout';
import { ROUTES } from './constants';
const rootRoute = createRootRoute({ component: RootLayout });
const productsRoute = createRoute({
getParentRoute: () => rootRoute,
path: ROUTES.products,
validateSearch: productListSearchSchema,
beforeLoad: ({ location }) => requirePermission('catalog.products.read', location.href),
component: lazyRouteComponent(() => import('../screen/products/page'), 'ProductsPage'),
pendingComponent: ListPageSkeleton,
});
export const router = createRouter({ routeTree: rootRoute.addChildren([productsRoute]) });
declare module '@tanstack/react-router' {
interface Register {
router: typeof router;
}
}
```
`apps/<app>/src/screen/products/page.tsx`
```tsx
import { useProductsPage } from '../../features/catalog';
import { ProductsTemplate } from './templates/products-template';
export function ProductsPage() {
const model = useProductsPage();
return <ProductsTemplate {...model} />;
}
```
## Testing
- Every feature ships Playwright specs for the happy path, the validation error path, and the server error path. Locate elements by role, label, or `data-testid`, never by CSS class.
- After implementing any UI, take Playwright screenshots at 1440, 1024, and 390 px wide and inspect them for: text overflowing its container, truncated labels without tooltips, overlapping elements, misaligned columns, invisible focus rings, low-contrast text, content hidden behind fixed headers, horizontal scrollbars on mobile, and empty areas where content should have loaded. Fix, re-screenshot, and repeat until clean, and record the checklist you used.
- Use `toHaveScreenshot()` for visual regression on island components and key screens. Update snapshots only after reviewing the diff.
- Run an axe scan (`@axe-core/playwright`, when the repo has it) with no serious or critical issues.
```ts
import { expect, test } from '@playwright/test';
test.describe('Edit product screen', () => {
test('saves changes and confirms with a toast', async ({ page }) => {
await page.goto('/products/42/edit');
await page.getByLabel('Product name').fill('Blue Ceramic Mug');
await page.getByRole('button', { name: 'Save changes to this product' }).click();
await expect(page.getByRole('status')).toContainText('Product "Blue Ceramic Mug" was saved');
});
test('shows a field error when the name is empty', async ({ page }) => {
await page.goto('/products/42/edit');
await page.getByLabel('Product name').fill('');
await page.getByRole('button', { name: 'Save changes to this product' }).click();
await expect(page.getByText('Enter a product name. It is shown to customers in the catalog.')).toBeVisible();
});
test('renders correctly at each breakpoint', async ({ page }) => {
for (const [name, width] of [['desktop', 1440], ['tablet', 1024], ['mobile', 390]] as const) {
await page.setViewportSize({ width, height: 900 });
await page.goto('/products/42/edit');
await expect(page).toHaveScreenshot(`product-edit-${name}.png`, { fullPage: true });
}
});
});
```
## Definition of Done (admin additions)
```
Structure and navigation
[ ] Title names the page and its object and matches the document title
[ ] Breadcrumbs show the full hierarchy with linked ancestors
[ ] Back button returns to the logical parent
[ ] Complex actions and flows have an info icon with their description and consequences
Access
[ ] Route guard, action gating, and sidebar filtering use the right permission
[ ] "No access" and 403 cases explain what happened
Data and states
[ ] Long lists are paginated on the server; page, size, sort, and filters are in the URL
[ ] Changing the page scrolls to the top of the table
[ ] Long processes show a progress bar, percentage, and current step
[ ] File uploads show a progress bar, percentage, and cancel
Visual
[ ] Page, navigation, card, and section surfaces are visibly distinct; status and accent colors meet AA
[ ] Enabled interactive elements use cursor: pointer; disabled ones use not-allowed
[ ] Sortable headers and every clickable element have an icon, hover, or active indicator
Stability and performance
[ ] No mount/unmount flicker on refetch or state change
[ ] Rows memoized (or React Compiler on), contexts split, Profiler checked for the heaviest interaction
Responsiveness and testing
[ ] Verified at desktop (≥ 1440), tablet (1024–1439), and mobile (0–1023); no horizontal page scroll
[ ] Screenshots at all three widths inspected, flaws fixed, re-verified
[ ] axe scan has no serious or critical issues
```

View File

@ -0,0 +1,309 @@
# B2C/B2B playbook
Public websites with 1–20 million visitors a day, like Amazon, eBay, and Digikala. Every kilobyte and millisecond is multiplied by millions of sessions. Most visitors arrive from search on mid-range phones, and many are logged out. Performance and SEO decide the architecture, the server renders every page fresh and caches nothing, and the codebase must stay maintainable as teams and features grow.
Contents: Targets · No server cache · Rendering · Server and client entries · Data flow · State and auth · Bundle and code splitting · Hydration and navigation · Images, fonts, and CSS · SEO and i18n · Responsiveness, testing, and monitoring · Example: caches, page, and parts · Definition of Done
## Targets
These are defaults; tighten them per product in the Spec Kit plan.
| Metric | Target |
|---|---|
| LCP, p75 of mobile field data | ≤ 2.5 s |
| INP, p75 | ≤ 200 ms |
| CLS, p75 | ≤ 0.1 |
| TTFB, p75 | ≤ 0.8 s |
| First-load JS per route, gzipped, framework included | ≤ 200 KB |
| Route-specific client JS, gzipped | ≤ 100 KB |
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.
## No server cache
The Next.js server renders a fresh page for every request and keeps nothing between requests: no prerendered or revalidated pages, and no cached data.
- Keep Cache Components (`cacheComponents` in `next.config.ts`) off, because it prerenders a static shell at build time. Every root layout declares `export const dynamic = 'force-dynamic'`, which renders each route at request time and sends every `fetch` with `no-store`. Metadata routes (`sitemap.ts`, `robots.ts`, generated icons and Open Graph images) are cached by default and no layout covers them, so each one declares it too.
- Never use `'use cache'`, `unstable_cache`, `fetch` caching (`cache: 'force-cache'`, `next: { revalidate, tags }`), the `revalidate` segment config, `dynamic = 'force-static'` or `'error'`, or `generateStaticParams`. The HTTP lib sends every server request with `cache: 'no-store'` (see [lib-http.md](lib-http.md#server-side-b2cb2b)).
- Never keep back-end data or rendered output in module scope, such as a `Map`, an LRU, or a memoized promise. Settings made once at startup, like env and the root `http` client, are fine.
- Caches that end with the request are fine: React `cache()` (the features' `caches/`) and the per-request `QueryClient`. So are caches in the browser, like the TanStack Query cache and the router cache.
- Nothing needs revalidating. After a mutation that changes server-rendered content, call `router.refresh()` and the server renders the page again.
- Every request pays for a full render, so keep it cheap: stream slow parts, fetch in parallel, and when a back-end call is slow, fix or cache it in the back end, never in Next.js.
## Rendering
- Server Components by default. Put `'use client'` only on interactive leaves, never on a layout or page.
- 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. One slow backend call must never block the whole page. Record each route's streamed 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
- Each project except apps exposes `src/index.ts`, safe to import anywhere, and `src/server.ts`, server only. `server.ts` starts with `import 'server-only';` and is exported as `@project/<name>/server`. Client code imports only `index.ts` entries, and `index.ts` never re-exports from `server.ts`.
- `server.ts` holds server-only capabilities: caches, page data loaders, SEO builders, device detection, the server HTTP configuration, and server-side integrations. Server-only files are exported only from `server.ts`, never from a module's `index.ts`.
- Repositories have no client-side dependencies, so they are exported from `index.ts` and run on both sides.
- A server page loader that combines several caches for one page's first paint sits in that page's `models/<page>/` folder (`load-<page>-page.ts`) and is exported only through `server.ts`.
- `bootstrap.server.ts` must run before server rendering: import it at the top of every root layout. `bootstrap.client.ts` must run before client components render, both during SSR and in the browser: import it first in the app's root client component, the one that renders the platform's `AppShell`. Client components render in a separate module graph, so values set by server-only code are invisible to them. Make both bootstraps idempotent.
- Never call `getEnv`, a repository, or a cache at module top level. Do it inside functions, so bootstrap has always run first.
- Bootstrap code for both sides, env included: [lib-env.md](lib-env.md#usage).
## Data flow
A request becomes a page in this order. The server steps run per request and keep nothing afterwards.
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 `<Suspense>` 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.
**Caches** (`features/<feature>/caches/`, server-only)
- Each cache is React's `cache()` around one repository call: `export const getProduct = cache((id: string) => productsRepository.get({ id }))`. React keeps the result for the current request only, so it's an allowed server cache (see No server cache).
- On the server, pages, loaders, `generateMetadata`, and server components read data only through caches, never through a repository directly. That's why ten components that need the same product send one request.
- Cache arguments are primitives, such as ids and page numbers. React compares arguments by identity, so `getProducts({ page })` would miss every time.
- Define caches at module level. A `cache()` created inside a component is new on every render.
- The module's entry is `server.ts`, with no `index.ts`, and the platform's `server.ts` re-exports it.
**Handing server data to client components**
- Props, for data the client part only shows or starts from: pass the `*Payload`, small and serializable. To stream it, pass the un-awaited promise and read it with `use()` inside `<Suspense>`.
- Query hydration, for data the client part keeps live (refetches, pagination, filters, or mutations that update it): prefetch into a `QueryClient` from `getQueryClient()` in `configs/react-query.ts`, with the cache as the `queryFn`, and render the part inside `<HydrationBoundary state={dehydrate(queryClient)}>`. The part's model queries the same key and starts with the data.
- An awaited prefetch puts the data in the HTML. Wrap the server component in `<Suspense>` so the await streams.
- An un-awaited prefetch doesn't block the part: the pending query is dehydrated and streams in, and the model reads it with `useSuspenseQuery`. Page or filter changes then go through `startTransition`, so the part keeps its content instead of falling back to the skeleton.
- A server prefetch calls the cache, never the repository, so a server component that awaits the same data in the same request shares the request.
**Data loaded only in the browser**
- Render on the server what search engines and the first paint need. Load in the browser only what's personal, below the fold, or shown on interaction, through a part model inside `<Suspense>` with a skeleton.
- A browser-only part uses `useQuery` and shows its skeleton while pending, or is loaded with `next/dynamic` from a client component: with `ssr: false` and a same-size `loading` skeleton when it renders at once, and without `ssr: false` when `LoadOnVisible` or an interaction already delays it ([rendering-patterns.md](rendering-patterns.md)). `useSuspenseQuery` is only for queries the server prefetched: any other query would run during SSR, where requests carry none of the user's cookies.
## State and auth
- `configs/react-query.ts`: `getQueryClient()` returns a new `QueryClient` on every server call and one shared instance in the browser. `staleTime` is above zero (60 s) so hydrated data isn't refetched on mount, queries don't retry (the HTTP lib does), 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.
- 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-b2cb2b)).
- 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 `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).
## Bundle and code splitting
- Import island, libs, and every other package by subpath (`@project/island/atoms/button`), never from a root barrel.
- Declare `sideEffects` in every package so unused modules are dropped.
- Load heavy client-only widgets (maps, charts, rich editors, galleries, video players, chat) with `next/dynamic` inside a client component, on interaction or when visible, with a same-size skeleton.
- Load third-party scripts from `packages/integrations` after hydration (`next/script` with `afterInteractive` or `lazyOnload`), never in the critical path.
- Check a dependency's gzipped size before adding it, and prefer what the stack already has.
- Load only the active locale and the namespaces the route uses.
## Hydration and navigation
- Render output must be identical on server and client: no `Date.now()`, `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.
- 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.
- 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)).
## 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.
- Fonts come from `island/fonts` as variable woff2. Preload only the critical face, use `font-display: swap`, and use a size-adjusted fallback so the swap doesn't shift layout. `next/font/local` does both.
- 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).
## SEO and i18n
- Build `generateMetadata` from `configs/seo.ts`: title, description, canonical URL, `hreflang` alternates, and Open Graph. Add JSON-LD for products, breadcrumbs, and the organization. Provide `sitemap.ts` and `robots.ts`.
- 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.
## Responsiveness, testing, and monitoring
- Each route has a mobile and a desktop template, and each template stays fluid across its device range. Touch targets are at least 44×44 px on mobile.
- The device is chosen on the server, so Playwright projects set both the user agent and the viewport, for example `devices['Pixel 7']` and `devices['Desktop Chrome']`. Screenshot both templates, inspect them, fix what you find, and repeat until clean.
- Report field web vitals per route (`useReportWebVitals` into the analytics integration), send errors to the Sentry integration, and review p75 per release.
## Example: caches, page, and parts
`platforms/<app>/src/shared/utils/get-device.ts`
```ts
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';
}
```
`platforms/<app>/src/features/catalog/caches/products.ts`
```ts
import 'server-only';
import { cache } from 'react';
import { productsRepository } from '../repositories/products';
import { RELATED_PRODUCTS_LIMIT } from './constants';
export const getProduct = cache((id: string) => productsRepository.get({ id }));
export const getRelatedProducts = cache((id: string) =>
productsRepository.listRelated({ id, limit: RELATED_PRODUCTS_LIMIT }),
);
export const getProductReviews = cache((id: string, page: number) => productsRepository.listReviews({ id, page }));
```
`platforms/<app>/src/features/catalog/caches/server.ts`
```ts
import 'server-only';
export { getProduct, getProductReviews, getRelatedProducts } from './products';
```
`platforms/<app>/src/server.ts`
```ts
import 'server-only';
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.
```tsx
import { getDevice, getProduct } from '@project/<platform>/server';
import type { Metadata } from 'next';
import { ProductDesktop } from './templates/product-desktop';
import { ProductMobile } from './templates/product-mobile';
type ProductPageProps = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: ProductPageProps): Promise<Metadata> {
const { id } = await params;
const product = await getProduct(id);
return { title: product.name, description: product.summary };
}
export default async function ProductPage({ params }: ProductPageProps) {
const { id } = await params;
const [device, product] = await Promise.all([getDevice(), getProduct(id)]);
return device === 'mobile' ? <ProductMobile product={product} /> : <ProductDesktop product={product} />;
}
```
The desktop template, a Server Component, renders the product at once and streams the two slower parts:
```tsx
<ProductSummary product={product} />
<Suspense fallback={<RelatedProductsSkeleton />}>
<RelatedProducts productId={product.id} />
</Suspense>
<Suspense fallback={<ProductReviewsSkeleton />}>
<ProductReviews productId={product.id} />
</Suspense>
```
`.../product/[id]/organisms/related-products/RelatedProducts.tsx`. The client only shows this part, so it stays a Server Component.
```tsx
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} />;
}
```
`.../product/[id]/organisms/product-reviews/ProductReviews.tsx`. The client pages through reviews, so this part hands its first page over through query hydration. `ReviewsList` is a client component that calls the part model.
```tsx
import { reviewKeys } from '@project/<platform>/features/catalog';
import { getProductReviews } from '@project/<platform>/server';
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { getQueryClient } from '../../../../../../configs';
import { ReviewsList } from './components/reviews-list';
import type { ProductReviewsProps } from './types';
export async function ProductReviews({ productId }: ProductReviewsProps) {
const queryClient = getQueryClient();
await queryClient.prefetchQuery({
queryKey: reviewKeys.list(productId, 1),
queryFn: () => getProductReviews(productId, 1),
});
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ReviewsList productId={productId} />
</HydrationBoundary>
);
}
```
`platforms/<app>/src/features/catalog/models/product/use-product-reviews-part.ts`. Page 1 comes from the server; later pages load in the browser while the current page stays visible.
```ts
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { productsRepository, reviewKeys } from '../../repositories/products';
export function useProductReviewsPart(productId: string) {
const [page, setPage] = useState(1);
const reviews = useQuery({
queryKey: reviewKeys.list(productId, page),
queryFn: ({ signal }) => productsRepository.listReviews({ id: productId, page }, { signal }),
placeholderData: keepPreviousData,
});
return { reviews, page, setPage };
}
```
`apps/<app>/src/configs/react-query.ts`. The app's root client component passes `getQueryClient()` to `QueryClientProvider`. Older TanStack Query v5 releases use the `isServer` constant instead of `environmentManager.isServer()`.
```ts
import { defaultShouldDehydrateQuery, environmentManager, QueryClient } from '@tanstack/react-query';
function makeQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: { staleTime: 60_000, retry: false },
dehydrate: {
shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending',
},
},
});
}
let browserQueryClient: QueryClient | undefined;
export function getQueryClient(): QueryClient {
if (environmentManager.isServer()) return makeQueryClient();
browserQueryClient ??= makeQueryClient();
return browserQueryClient;
}
```
## Definition of Done (B2C/B2B additions)
```
[ ] Fresh page per request: Cache Components off; every root layout and metadata route exports dynamic = 'force-dynamic'
[ ] No server cache: no 'use cache', unstable_cache, fetch caching, revalidate, or generateStaticParams; no back-end data kept in module scope
[ ] Server code reads data only through caches with primitive arguments; no page, loader, or server component calls a repository directly
[ ] Each client part gets server data as props or through query hydration; server prefetches call the cache
[ ] useSuspenseQuery only on queries the server prefetched
[ ] Each route's streamed parts are decided and written in the plan
[ ] 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
[ ] No hydration warnings; LCP image not lazy; images, fonts, and banners cause no layout shift
[ ] No store writes during server render; per-request QueryClient on the server
[ ] No cookie or local-storage reads during render; persisted stores rehydrate after mount
[ ] Metadata, canonical URL, hreflang, and structured data where relevant
[ ] Playwright passes on mobile and desktop device profiles; both templates screenshotted and inspected
```

View File

@ -0,0 +1,537 @@
# Code patterns
Reference implementations for each layer. Paths are relative to the project that owns the code: `platforms/<app>/src/` for B2C/B2B logic, `apps/<app>/src/` for admin panels, and `packages/<name>/src/` for shared packages. `@project` is the workspace scope. The `@project/libs/*` APIs shown follow the lib specs: `http` and `isHttpError` in [lib-http.md](lib-http.md), `storage` in [lib-local-storage.md](lib-local-storage.md), `cookie` in [lib-cookie.md](lib-cookie.md). `eventEmitter` stands for the repo's own lib; match its real signature.
Type-specific code lives in the playbooks: caches, the page entrypoint, and server-to-client data in [b2c-b2b.md](b2c-b2b.md), routes, guards, and screens in [admin-panels.md](admin-panels.md).
This file is the house code for each layer. Which design pattern to use, when, and where it lives is in [design-patterns.md](design-patterns.md).
Contents: Island component module · Tokens and Tailwind wiring · Repository · Action (with its event) · Validation, model, and server errors · Mutation with a valid cache · Store · Persisted store · Env
## Island component module
`atoms/button/variants.ts`
```ts
import { cva } from 'class-variance-authority';
export const buttonVariants = cva(
'inline-flex cursor-pointer items-center justify-center gap-2 rounded-md font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-action-primary disabled:cursor-not-allowed disabled:opacity-50',
{
variants: {
variant: {
primary: 'bg-action-primary text-on-action hover:bg-action-primary-hover',
secondary: 'border border-border-subtle bg-surface-card text-text-primary hover:bg-surface-muted',
danger: 'bg-status-danger text-on-action hover:bg-status-danger-hover',
},
size: {
sm: 'h-8 px-3 text-sm',
md: 'h-10 px-4 text-sm',
lg: 'h-11 px-5 text-base',
},
},
defaultVariants: { variant: 'primary', size: 'md' },
},
);
```
`atoms/button/types.ts`
```ts
import type { VariantProps } from 'class-variance-authority';
import type { ComponentPropsWithRef } from 'react';
import type { buttonVariants } from './variants';
export type ButtonProps = ComponentPropsWithRef<'button'> &
VariantProps<typeof buttonVariants> & {
isLoading?: boolean;
};
```
`atoms/button/Button.tsx`
```tsx
import { cn } from '../../tools/cn';
import { Spinner } from '../spinner';
import type { ButtonProps } from './types';
import { buttonVariants } from './variants';
export function Button({
className,
variant,
size,
isLoading = false,
disabled,
type = 'button',
children,
...props
}: ButtonProps) {
return (
<button
type={type}
className={cn(buttonVariants({ variant, size }), className)}
disabled={disabled || isLoading}
aria-busy={isLoading || undefined}
{...props}
>
{isLoading && <Spinner size="sm" />}
{children}
</button>
);
}
```
`atoms/button/index.ts`
```ts
export { Button } from './Button';
export type { ButtonProps } from './types';
export { buttonVariants } from './variants';
```
`tools/cn/cn.ts`
```ts
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
```
tailwind-merge doesn't know the theme. If `theme.css` adds a token it can't classify, such as a font size `text-body-sm` (which it reads as a color and drops next to `text-text-primary`), build `cn` with `extendTailwindMerge` and register the token.
## Tokens and Tailwind wiring
`styles/theme.css`: primitives are plain theme values, semantic tokens point at primitives and switch per theme, and `@theme inline` turns the semantic tokens into utilities (`bg-surface-card`, `text-text-muted`). Components use only the semantic utilities, so they never need `dark:` variants.
```css
@theme {
--color-neutral-0: #ffffff;
--color-neutral-50: #f4f6fa;
--color-neutral-900: #161b23;
--color-neutral-950: #0f1319;
--color-blue-500: #3b82f6;
--color-blue-600: #2563eb;
}
:root {
--surface-page: var(--color-neutral-50);
--surface-card: var(--color-neutral-0);
--action-primary: var(--color-blue-600);
}
.dark {
--surface-page: var(--color-neutral-950);
--surface-card: var(--color-neutral-900);
--action-primary: var(--color-blue-500);
}
@theme inline {
--color-surface-page: var(--surface-page);
--color-surface-card: var(--surface-card);
--color-action-primary: var(--action-primary);
}
```
This is an excerpt. The real file defines every semantic token the components use, such as `text-primary`, `text-muted`, `border-subtle`, `on-action`, the `status-*` colors, and their hover states.
`styles/island.css`
```css
@import './theme.css';
@import './fonts.css';
@import './utilities.css';
@source '../';
```
`apps/<app>/src/styles/app.css`
```css
@import 'tailwindcss' source('../');
@import '@project/island/styles/island.css';
@source '../../../../platforms/<app>/src';
```
Tailwind generates only the classes it finds in registered sources. island registers itself in `island.css`; the app registers its own `src/`, its platform, and any integration that renders UI. CSS `@import` resolves package names through package.json `exports`, not TypeScript path aliases, so path-alias workspaces import `island.css` by relative path.
## Repository
`features/auth/entities/user/types.ts`
```ts
export type UserRole = 'admin' | 'operator';
export type User = {
id: string;
full_name: string;
role: UserRole;
};
```
`features/auth/repositories/auth/types.ts`
```ts
import type { User, UserRole } from '../../entities/user';
export type LoginArgs = { phone: string; password: string };
export type LoginDto = { mobile: string; password: string };
export type LoginResponseDto = { user: User; is_first_login: boolean };
export type LoginPayload = {
user: { id: string; fullName: string; role: UserRole };
isFirstLogin: boolean;
};
```
`features/auth/repositories/auth/mappers.ts`
```ts
import type { LoginArgs, LoginDto, LoginPayload, LoginResponseDto } from './types';
export function toLoginDto(args: LoginArgs): LoginDto {
return { mobile: args.phone, password: args.password };
}
export function toLoginPayload(dto: LoginResponseDto): LoginPayload {
return {
user: { id: dto.user.id, fullName: dto.user.full_name, role: dto.user.role },
isFirstLogin: dto.is_first_login,
};
}
```
`features/auth/repositories/auth/constants.ts`
```ts
export const AUTH_ENDPOINTS = {
login: '/auth/login',
logout: '/auth/logout',
refresh: '/auth/refresh',
} as const;
```
`features/auth/http.ts`. Every feature has one; this feature needs nothing special, so it only extends the root. A feature with its own service sets `baseUrl`, headers, timeout, or retry here (see [lib-http.md](lib-http.md#root-and-feature-clients)).
```ts
import { http } from '@project/libs/http';
export const authHttp = http.extend({});
```
`features/auth/repositories/auth/auth.ts`. Repositories send requests only through their feature's client and never through the root `http`.
```ts
import { authHttp } from '../../http';
import { AUTH_ENDPOINTS } from './constants';
import { toLoginDto, toLoginPayload } from './mappers';
import type { LoginArgs, LoginPayload, LoginResponseDto } from './types';
export const authRepository = {
async login(args: LoginArgs): Promise<LoginPayload> {
const response = await authHttp.post<LoginResponseDto>(AUTH_ENDPOINTS.login, toLoginDto(args));
return toLoginPayload(response);
},
};
```
Read methods take an optional last parameter `{ signal?: AbortSignal }` and forward it, so TanStack Query can cancel them (see Mutation with a valid cache).
`features/auth/repositories/auth/index.ts` exports no `*Dto`:
```ts
export { authRepository } from './auth';
export { AUTH_ENDPOINTS } from './constants';
export type { LoginArgs, LoginPayload } from './types';
```
Query keys sit in the repository's `constants.ts`, start with the domain, and are hierarchical so invalidation is precise. `features/catalog/repositories/products/constants.ts`:
```ts
import type { ListProductsArgs } from './types';
export const PRODUCTS_ENDPOINT = '/catalog/products';
export const productKeys = {
all: ['catalog', 'products'] as const,
lists: () => [...productKeys.all, 'list'] as const,
list: (args: ListProductsArgs) => [...productKeys.lists(), args] as const,
details: () => [...productKeys.all, 'detail'] as const,
detail: (id: string) => [...productKeys.details(), id] as const,
};
```
## Action
`features/auth/constants.ts`. Event names are `<feature>.<action>`.
```ts
export const AUTH_EVENTS = {
login: 'auth.login',
logout: 'auth.logout',
} as const;
export const LAST_PHONE_STORAGE_KEY = 'last-phone';
```
`features/auth/actions/login/actions.ts`. The repository throws the normalized `HttpError` when the request fails, so reaching the next line means the response was successful. The caller handles the error.
```ts
import { eventEmitter } from '@project/libs/event-emitter';
import { storage } from '@project/libs/local-storage';
import { useAuthStore } from '../../../../stores/auth';
import { accessRepository } from '../../../access';
import { AUTH_EVENTS, LAST_PHONE_STORAGE_KEY } from '../../constants';
import { authRepository, type LoginArgs } from '../../repositories/auth';
export async function login(args: LoginArgs, { emit = true }: { emit?: boolean } = {}): Promise<'ok'> {
const { user, isFirstLogin } = await authRepository.login(args);
const permissions = await accessRepository.getMyPermissions();
useAuthStore.getState().setSession({ user, permissions, isFirstLogin });
storage.setItem(LAST_PHONE_STORAGE_KEY, args.phone);
if (emit) eventEmitter.emit(AUTH_EVENTS.login, { userId: user.id });
return 'ok';
}
```
- Every action emits its event as its last step, so a failed step throws before the emit and listeners only hear about completed operations.
- `{ emit: false }` is for callers that must not trigger listeners, such as an action that runs another action as one of its steps and emits its own event.
- Code that reacts to an action (analytics, another feature's refresh) subscribes to its event instead of being called from the action. Subscribe once, in an effect of the `AppShell`, and unsubscribe in its cleanup.
## Validation, model, and server errors
`shared/validations/base-validations.ts`. Messages are i18n keys; the field component translates them. Each message tells the user how to fix the value, for example "Enter an 11-digit mobile number that starts with 09."
```ts
import { MOBILE_REGEX } from '@project/libs/regex';
import * as v from 'valibot';
export const requiredString = (message: string) => v.pipe(v.string(), v.trim(), v.nonEmpty(message));
export const mobileNumber = (message: string) =>
v.pipe(v.string(), v.trim(), v.regex(MOBILE_REGEX, message));
```
`shared/validations/auth-validations.ts`
```ts
import * as v from 'valibot';
import { mobileNumber, requiredString } from './base-validations';
export const loginSchema = v.object({
phone: mobileNumber('validation:phone.invalid'),
password: requiredString('validation:password.required'),
});
```
`shared/validations/types.ts`
```ts
import type * as v from 'valibot';
import type { loginSchema } from './auth-validations';
export type LoginFormValues = v.InferOutput<typeof loginSchema>;
```
`shared/utils/apply-server-errors.ts`: field errors go under their fields (the first one gets focus), errors that match no field go to a form-level alert, and a toast summarizes the failure.
```ts
import { isHttpError } from '@project/libs/http';
import type { FieldValues, Path, UseFormReturn } from 'react-hook-form';
import { toast } from 'sonner';
export function applyServerErrors<T extends FieldValues>(
form: UseFormReturn<T>,
error: unknown,
fallbackMessage: string,
): void {
if (!isHttpError(error)) {
toast.error(fallbackMessage, { duration: Infinity });
return;
}
const fieldErrors = Object.entries(error.fieldErrors ?? {});
fieldErrors.forEach(([field, message], index) => {
form.setError(field as Path<T>, { type: 'server', message }, { shouldFocus: index === 0 });
});
if (fieldErrors.length === 0) {
form.setError('root.server', { type: 'server', message: error.message });
}
toast.error(error.message, { description: error.hint, duration: Infinity });
}
```
`features/auth/models/login/use-login-page.ts` (admin panel). In a B2C/B2B platform the model is the same, with `useRouter` from `next/navigation`.
```ts
import { valibotResolver } from '@hookform/resolvers/valibot';
import { useNavigate } from '@tanstack/react-router';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { applyServerErrors } from '../../../../shared/utils';
import { loginSchema, type LoginFormValues } from '../../../../shared/validations';
import { login } from '../../actions/login';
export function useLoginPage() {
const { t } = useTranslation('auth');
const navigate = useNavigate();
const form = useForm<LoginFormValues>({
resolver: valibotResolver(loginSchema),
mode: 'onTouched',
defaultValues: { phone: '', password: '' },
});
const submit = form.handleSubmit(async (values) => {
try {
await login(values);
toast.success(t('login.success'));
await navigate({ to: '/' });
} catch (error) {
applyServerErrors(form, error, t('login.failed'));
}
});
return { form, submit, isSubmitting: form.formState.isSubmitting };
}
```
`mode: 'onTouched'` validates a field on its first blur and on every change after that. The submit button is disabled only while `isSubmitting`, never because the form is invalid, so users can click it to find out what is wrong.
## Mutation with a valid cache
After every create, update, or delete, set the detail, patch the affected lists, then invalidate the lists to reconcile in the background. When patching isn't practical, invalidate every key that can contain the entity (details, lists, counts, dashboards). Never rely on `staleTime` expiring.
Use optimistic updates only for quick toggles (active/inactive, favorite), always with a rollback in `onError` and a toast explaining the failure.
`features/catalog/models/product-edit/use-product-edit-page.ts`
```ts
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { productKeys, productsRepository, type ProductsPagePayload } from '../../repositories/products';
export function useProductEditPage(productId: string) {
const { t } = useTranslation('catalog');
const queryClient = useQueryClient();
const product = useQuery({
queryKey: productKeys.detail(productId),
queryFn: ({ signal }) => productsRepository.get({ id: productId }, { signal }),
});
const save = useMutation({
mutationFn: productsRepository.update,
onSuccess: (updated) => {
queryClient.setQueryData(productKeys.detail(updated.id), updated);
queryClient.setQueriesData<ProductsPagePayload>({ queryKey: productKeys.lists() }, (page) =>
page ? { ...page, items: page.items.map((item) => (item.id === updated.id ? updated : item)) } : page,
);
void queryClient.invalidateQueries({ queryKey: productKeys.lists() });
toast.success(t('product.saved', { name: updated.name }));
},
});
return { product, save };
}
```
## Store
`stores/auth/types.ts`
```ts
import type { Permission } from '../../features/access';
import type { LoginPayload } from '../../features/auth';
export type Session = {
user: LoginPayload['user'];
permissions: Permission[];
isFirstLogin: boolean;
};
export type AuthState = {
session: Session | null;
setSession: (session: Session) => void;
clearSession: () => void;
};
```
`stores/auth/auth-store.ts`. Components subscribe to the smallest slice they render, never to the whole store.
```ts
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import type { Permission } from '../../features/access';
import type { AuthState } from './types';
export const useAuthStore = create<AuthState>()(
immer((set) => ({
session: null,
setSession: (session) =>
set((state) => {
state.session = session;
}),
clearSession: () =>
set((state) => {
state.session = null;
}),
})),
);
export const useCurrentUser = () => useAuthStore((state) => state.session?.user);
export const useHasPermission = (permission: Permission) =>
useAuthStore((state) => state.session?.permissions.includes(permission) ?? false);
```
B2C/B2B: never write to a store during server render (see b2c-b2b.md).
## Persisted store
A store that survives a reload keeps its data in local storage through the `storage` adapter, so the key lands under the app's prefix (`shop.session.cart`). `stores/cart/cart-store.ts`:
```ts
import { storage } from '@project/libs/local-storage';
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type { CartState } from './types';
export const useCartStore = create<CartState>()(
persist(
immer((set) => ({
items: [],
addItem: (item) =>
set((state) => {
state.items.push(item);
}),
clear: () =>
set((state) => {
state.items = [];
}),
})),
{
name: 'session.cart',
storage: createJSONStorage(() => storage),
version: 1,
partialize: (state) => ({ items: state.items }),
skipHydration: true,
},
),
);
```
- `name` is the key. `session.` marks it as the logged-in user's data, so logout's `storage.clearByPrefix('session.')` removes it.
- `partialize` persists only what must survive a reload. Bump `version` and add `migrate` when the shape changes.
- B2C/B2B keeps `skipHydration: true` and rehydrates after mount, so the server render and the first browser render match. In the platform's `AppShell`: `useEffect(() => { void useCartStore.persist.rehydrate(); }, []);`. Admin panels render only in the browser and can drop `skipHydration`.
## Env
The app's `env/` files, a project's `setEnv` and `getEnv`, and both bootstraps: [lib-env.md](lib-env.md#usage).

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,371 @@
# Project structure
`<placeholders>` are names you choose. `@project` stands for the workspace's npm scope.
Contents: Top level · B2C/B2B app · Platform · Admin panel app · Feature anatomy · Shared · island · libs, integrations, and tools packages · Env flow · Nx tags and boundaries · Exports and tree-shaking
## Top level
```
apps/ # deployable apps
platforms/ # B2C/B2B only: each app's logic, one project per app
packages/
├── island/ # design system (atomic design)
├── libs/ # framework-agnostic libraries, e.g. http and env
├── integrations/ # third-party integrations
└── tools/ # shared runtime tools
tools/ # workspace scripts for AI, Nx, and the repo, e.g. a doc validator
```
Three folders are named `tools`. Keep them apart:
- Root `tools/`: scripts that run in a terminal, in CI, or through Nx (generators, validators). App code never imports them. TypeScript scripts run with jiti.
- `packages/tools/`: shared runtime tools that apps and projects import.
- `packages/island/src/tools/`: design-system tools such as `cn`, `cvx`, `icon-sprite-plugin`, and `icon-name-extraction`.
## B2C/B2B app (Next.js)
```
apps/<app>/src/
├── bootstrap/
│ ├── bootstrap.client.ts # runs before client components render (SSR and browser)
│ ├── bootstrap.server.ts # runs once on the server before rendering
│ └── index.ts
├── i18n/
│ ├── i18n.ts
│ └── index.ts
├── app/ # Next.js App Router
│ └── (auth)/
│ ├── layout.tsx
│ ├── loading.tsx
│ └── auth/
│ └── login/
│ ├── page.tsx
│ ├── organisms/ # optional: organisms only this route uses
│ └── templates/ # optional: this route's mobile and desktop templates
├── styles/
│ ├── app.css # Tailwind entry; imports island.css
│ └── index.ts
├── configs/
│ ├── seo.ts
│ ├── react-query.ts
│ └── index.ts
├── constants/
│ ├── auth.ts # e.g. the OTP re-send timeout
│ └── index.ts
└── env/ # the only code that reads process.env (see lib-env.md)
├── env.client.ts # public variables: createClientEnv
├── env.server.ts # server variables: createServerEnv; import 'server-only'
├── index.ts # clientEnv
└── server.ts # serverEnv; import 'server-only'
```
- Pages are thin entrypoints. A page picks the mobile or the desktop template on the server, so no component branches on viewport size.
- Every route level may keep its own `organisms/` and `templates/`, shaped like island organisms. They are not routable because they contain no `page.tsx`.
- `styles/`, `configs/`, and `constants/` grow as needed; each keeps an `index.ts`.
- The app holds no features, stores, or business logic; those live in `platforms/<app>/`.
## Platform (B2C/B2B only)
```
platforms/<app>/src/
├── app/
│ ├── app-shell/ # top-level provider shell shared by the mobile and desktop views
│ │ ├── AppShell.tsx
│ │ ├── types.ts
│ │ └── index.ts
│ ├── guards/ # e.g. the route authentication guard
│ │ └── <guard-name>/
│ │ ├── <guard-name>.ts or <GuardName>.tsx
│ │ └── index.ts
│ └── navigation/
│ ├── navigation.ts # typed route paths and navigation menus
│ ├── constants.ts
│ ├── types.ts
│ ├── hooks/
│ │ └── use-<hook-name>.ts
│ ├── components/ # navigation UI, shaped like organisms
│ └── index.ts
├── features/ # DDD, see Feature anatomy
├── stores/ # one store per feature or domain
├── shared/ # see Shared
├── index.ts
└── server.ts
```
## Admin panel app (React + TanStack Router)
```
apps/<app>/src/
├── bootstrap/
│ ├── bootstrap.ts # runs once before the router renders
│ └── index.ts
├── i18n/
│ ├── i18n.ts
│ └── index.ts
├── app-shell/ # top-level provider shell
│ ├── AppShell.tsx
│ ├── types.ts
│ └── index.ts
├── guards/ # e.g. authentication and permission guards
│ └── <guard-name>/
│ ├── <guard-name>.ts or <GuardName>.tsx
│ └── index.ts
├── navigation/
│ ├── navigation.ts # code-based route tree; lazy-loads screen/**/page.tsx
│ ├── constants.ts # route paths, sidebar items and their permissions
│ ├── types.ts
│ ├── hooks/
│ │ └── use-<hook-name>.ts
│ ├── components/ # root layout, sidebar, breadcrumbs; shaped like organisms
│ └── index.ts
├── screen/ # mirrors the route tree
│ └── <page-name>/
│ ├── page.tsx # thin entry: calls the model, renders the template
│ ├── organisms/ # optional: organisms only this screen uses
│ ├── templates/ # optional
│ └── <child-page-name>/
│ └── page.tsx
├── features/ # DDD, see Feature anatomy
├── stores/ # one store per feature or domain
└── shared/ # see Shared
```
- Every level of `screen/` may keep its own `organisms/` and `templates/`, shaped like island organisms.
- When the app needs them, add `env/`, `styles/`, and `configs/` shaped like the B2C/B2B app's. Its `env/` has only `env.client.ts` and `index.ts`.
## Feature anatomy (platforms and admin apps)
```
features/<feature>/
├── entities/ # back-end data model: types, enums, unions
│ └── <entity-name>/
│ ├── types.ts
│ └── index.ts
├── repositories/ # request + return data; no client-side dependencies
│ └── <repository-name>/
│ ├── <repository-name>.ts
│ ├── types.ts # e.g. LoginArgs, LoginDto, LoginResponseDto, LoginPayload
│ ├── mappers.ts # *Args → *Dto (outgoing), *ResponseDto → *Payload (incoming)
│ ├── constants.ts # endpoints and query keys
│ └── index.ts
├── caches/ # B2C/B2B platforms only: server-only React cache() reads
│ ├── <cache-name>.ts
│ ├── types.ts
│ ├── constants.ts
│ └── server.ts # the module's entry; no index.ts
├── actions/
│ └── <action-name>/
│ ├── actions.ts # the operation from start to end; emits its event
│ └── index.ts
├── models/ # logic per page and per part, as hooks
│ ├── login/ # a page with one model
│ │ ├── use-login-page.ts
│ │ ├── types.ts
│ │ ├── constants.ts
│ │ └── index.ts
│ └── shipment/ # a page model plus one model per part
│ ├── use-shipment-page.ts
│ ├── use-shipment-address-part.ts
│ ├── use-shipment-legal-part.ts
│ ├── use-shipment-bill-part.ts
│ └── index.ts
├── http.ts # the feature's HTTP client: http.extend(...); used only by its repositories
├── types.ts
├── constants.ts
└── index.ts # never exports the http.ts client
```
Rules inside a feature:
- Layers import only from earlier layers: entities → repositories → actions → models → UI.
- Repositories import only entities, libs, the feature's `http.ts`, and their own files. Actions may also use stores and browser libs such as `storage`, `cookie`, and the event emitter. Models may also use actions, stores, and validations.
- Caches sit beside that chain, on the server: they import only entities, repositories, and their own files, and only server code imports them (server page loaders in `models/`, pages, `generateMetadata`, and server components). Details: [b2c-b2b.md](b2c-b2b.md#data-flow).
- Every action takes an optional last parameter `{ emit?: boolean }`, default `true`, and emits its `<feature>.<action>` event from the feature's `constants.ts` when its steps succeed.
- A page model owns what its parts share, such as the current step and the final submit. Each part model owns its part's data and form.
- `http.ts` exports one client, `http.extend(...)`, named after the feature (`catalogHttp`). It may set the base URL, headers, timeout, retry, and feature-only interceptors. It never sets refresh, credentials, or cookie forwarding; the type of `extend` rejects them. Details: [lib-http.md](lib-http.md#root-and-feature-clients).
- Models call repositories directly for queries. Mutations with side effects beyond the request go through an action.
- `*Payload` is the only repository type used outside the repository. If server field names differ from `*Args` names, the mappers translate the server's `fieldErrors` keys too.
- Another feature is imported only through its `index.ts`.
## Shared
```
shared/
├── constants/
│ ├── <constant-name>.ts
│ └── index.ts
├── utils/
│ ├── <util-name>.ts
│ └── index.ts
└── validations/
├── types.ts
├── constants.ts
├── base-validations.ts
├── <feature>-validations.ts
└── index.ts
```
`shared/` never imports from `features/`, `stores/`, `app/`, `screen/`, or `navigation/`.
## island (`packages/island`)
```
packages/island/src/
├── atoms/
│ └── <component-name>/ # component module
├── molecules/ # like atoms
├── organisms/
│ └── <component-name>/ # component module + private components/ and hooks/
├── templates/ # like organisms
├── primitives/ # non-visual structural pieces, e.g. portal; like organisms
├── tools/
│ └── <tool-name>/ # e.g. cn, cvx, icon-sprite-plugin, icon-name-extraction
│ ├── <tool-name>.ts or <tool-name>.tsx
│ ├── types.ts
│ ├── constants.ts
│ └── index.ts
├── styles/
│ ├── island.css # entry that apps import into their Tailwind v4 CSS
│ ├── theme.css # primitive and semantic tokens
│ ├── utilities.css # custom @utility definitions
│ └── fonts.css # @font-face rules for fonts/
├── env/ # island's env: setEnv and getEnv, filled by the app's bootstrap
│ ├── env.ts
│ ├── types.ts
│ └── index.ts
├── icons/
│ ├── symbol-defs.svg # sprite generated by Icomoon
│ └── selection.json # Icomoon snapshot; re-import it into Icomoon to update the set
├── fonts/ # every app's fonts, e.g. yekan-bakh-vf.woff2
├── constants.ts # island-level constants
├── index.ts
└── server.ts # B2C/B2B only
```
Component module:
| Entry | Required | Holds |
|---|---|---|
| `<ComponentName>.tsx` | Yes | The component |
| `types.ts` | Yes | Every type the component needs, including its props |
| `variants.ts` | Yes | The cva definitions. A non-visual primitive with no styles may skip it |
| `constants.ts` | No | Component-level constants |
| `index.ts` | Yes | The public API, re-exported by name |
| `components/` | Organisms, templates, primitives | Private sub-components shaped like atoms; never imported from outside, except a compound component's named parts, which its `index.ts` re-exports ([design-patterns.md](design-patterns.md)) |
| `hooks/` | Organisms, templates, primitives | Private `use-<hook-name>.ts` hooks |
Tools:
- `icon-sprite-plugin` is a build and dev plugin. It optimizes the SVGs with svgo and writes the final sprite into each app's `public/` folder. Build-time tools are imported only from build configs, never from app code.
- `icon-name-extraction` extracts icon names from the Icomoon files, for example to type the `Icon` component's `name` prop.
## libs, integrations, and tools packages
```
packages/libs/src/<lib-name>/ # e.g. http, env, error-handler, cookie, local-storage,
├── <lib-name>.ts # custom prototypes, regex, event-emitter
├── types.ts
├── constants.ts
└── index.ts
packages/integrations/src/<integration-name>/ # e.g. sentry, analytics
├── <integration-name>.ts
├── components/ # shaped like organisms
├── hooks/
│ └── use-<hook-name>.ts
├── constants.ts
├── types.ts
└── index.ts
packages/tools/src/<tool-name>/ # shared runtime tools
├── <tool-name>.ts
├── types.ts
├── constants.ts
└── index.ts
```
- libs are framework-agnostic: no React, Next.js, or TanStack imports. They never read env; the app's bootstrap passes their settings through `configure`.
- A lib may split its main file into more files when it grows. `http` does; its layout is in lib-http.md.
- Side-effect modules such as custom prototype extensions must be listed in `sideEffects` (see Exports).
Fundamental libs have full specs:
| Lib | Instance | Owns | Spec |
|---|---|---|---|
| `http` | Root `http`; one `http.extend(...)` client per feature | Every request: verbs, upload and download, interceptors, retry, one refresh at a time on 401, abort, `HttpError`; cookie forwarding on the B2C/B2B server | [lib-http.md](lib-http.md) |
| `env` | `createClientEnv`; `createServerEnv` (server) | Validating the app's env: public variables on both sides, server variables on the server only | [lib-env.md](lib-env.md) |
| `cookie` | `cookie` | Browser cookies for small values the server needs (locale, theme); never tokens | [lib-cookie.md](lib-cookie.md) |
| `local-storage` | `storage` | Prefixed, client-only, non-critical data and persisted zustand stores; never tokens or personal data | [lib-local-storage.md](lib-local-storage.md) |
`cookie` and `storage` are browser-only and export nothing from `server.ts`. `http` exports `configureServerHttp` from `server.ts`. `env` exports `createServerEnv` from its own `env/server.ts`, which the project's `server.ts` re-exports.
## Env flow
1. The app declares its variables in `apps/<app>/src/env/` and validates them with the env lib: `createClientEnv` for public variables and, in B2C/B2B, `createServerEnv` for server variables. These files are the only code that reads `process.env` or `import.meta.env`, and a bad variable stops the app with one error that lists every problem.
2. Every other project that reads env has `src/env/` (`env.ts`, `types.ts`, `index.ts`) with `setEnv`, which stores its own values, and `getEnv`, which returns them and throws a clear error before `setEnv` has run. Its code reads env only through `getEnv`, inside functions, never at module top level.
3. At startup the app's bootstrap calls each project's `setEnv` with the values that project needs. Projects never import the app, so the dependency graph stays acyclic. Libs never read env: the bootstrap passes their settings through `configure`.
4. B2C/B2B: `bootstrap.server.ts` fills the server module graph and may pass server-side values, such as an internal service address; `bootstrap.client.ts` fills the client module graph with public values only. Public variables use the `NEXT_PUBLIC_` prefix and are listed one by one in `runtimeEnv`, because Next.js inlines only literal `process.env.NEXT_PUBLIC_*` references. Admin apps use only `createClientEnv`, from `bootstrap.ts`, with their bundler's public prefix.
Code: [lib-env.md](lib-env.md).
## Nx tags and boundaries
Default tags. Reuse the repo's own tags if it already has them.
| Project | Tags |
|---|---|
| `apps/<app>` | `type:app`, `scope:<app>` |
| `platforms/<app>` | `type:platform`, `scope:<app>` |
| `packages/integrations` | `type:integration`, `scope:shared` |
| `packages/island` | `type:ui`, `scope:shared` |
| `packages/libs` | `type:lib`, `scope:shared` |
| `packages/tools` | `type:tool`, `scope:shared` |
`@nx/enforce-module-boundaries` constraints, the only ESLint rules the repo runs:
| Source tag | May depend on |
|---|---|
| `type:app` | `type:platform`, `type:integration`, `type:ui`, `type:lib`, `type:tool` |
| `type:platform` | `type:integration`, `type:ui`, `type:lib`, `type:tool` |
| `type:integration` | `type:ui`, `type:lib`, `type:tool` |
| `type:ui` | `type:lib`, `type:tool` |
| `type:lib` | `type:tool` |
| `type:tool` | Nothing |
| `scope:<app>` | `scope:<app>`, `scope:shared` |
| `scope:shared` | `scope:shared` |
Layer rules inside a project are checked in review, or by `eslint-plugin-boundaries` when the repo configures it:
- island: no import from a higher atomic level; an organism's `components/` and `hooks/` stay private.
- features: the layer order in Feature anatomy.
- `shared/`: imports nothing above it.
## Exports and tree-shaking
Expose each module on its own subpath. With package.json `exports` (Nx workspaces that use TypeScript project references):
```json
{
"name": "@project/island",
"sideEffects": ["**/*.css"],
"exports": {
".": "./src/index.ts",
"./server": "./src/server.ts",
"./atoms/*": "./src/atoms/*/index.ts",
"./molecules/*": "./src/molecules/*/index.ts",
"./organisms/*": "./src/organisms/*/index.ts",
"./templates/*": "./src/templates/*/index.ts",
"./primitives/*": "./src/primitives/*/index.ts",
"./tools/*": "./src/tools/*/index.ts",
"./env": "./src/env/index.ts",
"./styles/*": "./src/styles/*"
}
}
```
Workspaces that use `tsconfig.base.json` path aliases instead map `"@project/island": ["packages/island/src/index.ts"]` and `"@project/island/*": ["packages/island/src/*"]`.
- `sideEffects`: pure TypeScript modules have none. List every file that must run on import, such as CSS and custom prototype extensions; otherwise bundlers drop it.
- The root `index.ts` re-exports every module by name, so `@project/island` and `@project/island/atoms/button` expose the same symbols.
- A module with its own `server.ts` also gets a `<module>/server` subpath, for example `"./env/server": "./src/env/server.ts"` in libs. The project's `server.ts` re-exports it, so `@project/libs/server` and `@project/libs/env/server` expose the same symbols.

View File

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

View File

@ -0,0 +1,161 @@
# Rendering and loading patterns
This file takes the rendering and performance patterns from patterns.dev and decides, for each project type, whether to use each one and which tool implements it. The playbooks, [b2c-b2b.md](b2c-b2b.md) and [admin-panels.md](admin-panels.md), hold the details and win 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
## Rendering patterns
B2C/B2B apps render every page on the server for each request and stream it. Admin panels are client-side rendered SPAs, so the server rendering patterns don't apply to them.
| Pattern | B2C/B2B | Admin panel | How here |
|---|---|---|---|
| Client-side rendering | Parts only | Always | A B2C/B2B page renders only its browser-only parts in the browser ([b2c-b2b.md](b2c-b2b.md#data-flow)). An admin panel renders every screen there, each lazy-loaded behind a skeleton ([admin-panels.md](admin-panels.md#screens-and-routing)). |
| Server-side rendering | Always | Doesn't apply | Render every page fresh for each request, and read data through caches ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). |
| Static rendering | Never | Doesn't apply | Nothing renders at build time. Keep each request cheap instead (first note below). |
| Incremental static generation | Never | Doesn't apply | Nothing needs revalidating: after a mutation, `router.refresh()` renders the page again ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). |
| Partial prerendering | Never | Doesn't apply | It needs Cache Components, which stay off. `loading.tsx` and `<Suspense>` give an early first paint instead ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| Streaming server-side rendering | Always | Doesn't apply | 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 | Doesn't apply | Keep components on the server. Only interactive leaves get `'use client'` ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| Selective hydration | Automatic | Doesn't apply | Give each independent part its own `<Suspense>` boundary, so it hydrates on its own ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| Progressive hydration | Through Suspense | Doesn't apply | 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 | Doesn't apply | 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 | Rare | B2C/B2B: 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. Admin panel: TanStack Router's `defaultViewTransition` or a link's `viewTransition` option, which call the browser's View Transitions API; don't add React's `<ViewTransition>` as well. Animate only what helps orientation, such as a product image moving into its detail page, and turn it off under `prefers-reduced-motion`. |
- B2C/B2B 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.
- 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.
## Loading patterns
The budgets these patterns protect are in [b2c-b2b.md](b2c-b2b.md#targets) and [admin-panels.md](admin-panels.md#performance). Record each route's deferred parts and what triggers them in the plan's `research.md` ([spec-kit.md](spec-kit.md#plan-contents)).
| Pattern | B2C/B2B | Admin panel | How here |
|---|---|---|---|
| Static import | Default | Default | A static import in a `'use client'` file ships to the browser, and one reachable from the admin shell (`navigation.ts`, the `AppShell`, bootstrap) ships in the shell bundle. Put heavy modules behind a dynamic import. |
| Dynamic import | `next/dynamic` in a client component | `lazyRouteComponent`, `React.lazy` | Select the named export: `.then((mod) => mod.Chart)` for `next/dynamic`, `.then((mod) => ({ default: mod.Chart }))` for `React.lazy`. For code that isn't a component, use `await import()` in the event handler. In a `Record` map from key to component inside a client component, such as a CMS block type, make each heavy entry a `next/dynamic` or `React.lazy` component, so the map doesn't pull every entry into the route's bundle. A map in a Server Component needs nothing: only the client entries it renders ship. |
| Import on visibility | Widgets below the fold | Widgets below the fold | Wrap the lazy component in island's `LoadOnVisible` primitive (code below). |
| Import on interaction | Heavy widgets and embeds | Editors, viewers, modal content | Start the download on `pointerenter` or `focus`, and render on click. A static facade (patterns.dev's word for a placeholder, unrelated to the GoF Facade in design-patterns.md) stands in for video, maps, and chat until then (code below). |
| Route-based splitting | Automatic | Every screen | The App Router splits each route segment. Admin routes load their screens with `lazyRouteComponent` ([admin-panels.md](admin-panels.md#screens-and-routing)). |
| Bundle splitting | Automatic | Automatic | Steer it with small client boundaries and dynamic imports rather than the bundler's chunk settings, and check each route against its budget. |
| Tree shaking | Always | Always | Use named re-exports without `export *`, subpath imports, and `sideEffects` in every package ([project-structure.md](project-structure.md#exports-and-tree-shaking)). |
| PRPL | Built in | Built in | Preload critical files (next row). Render the route with the streamed server render, or with the admin shell and a skeleton. Pre-cache only through prefetch, because a service worker is outside the stack and needs approval. Lazy-load the rest with route splitting and dynamic imports. |
| Preload | LCP image, critical font | Rarely | Preload what [b2c-b2b.md](b2c-b2b.md#images-fonts-and-css) lists, and use React 19's resource functions for other origins and late files (notes below). |
| Prefetch | `next/link` default | On intent | Keep `next/link`'s default prefetch (notes below). In an admin panel, set `defaultPreload: 'intent'` on `createRouter`, and call `prefetchQuery` on hover ([admin-panels.md](admin-panels.md#data-and-cache)). |
| Loading sequence | Always | Always | Load the stylesheet, the critical font, and the LCP image first, then first-party JavaScript, then third parties after hydration. An admin panel loads its shell, then the route chunk behind its skeleton, then widgets. |
| Third-party loading | After hydration | After the shell renders | Load from `packages/integrations` with `next/script` and `afterInteractive` or `lazyOnload` ([b2c-b2b.md](b2c-b2b.md#bundle-and-code-splitting)). In an admin panel, the integration's loader runs in an effect of the `AppShell`. `@next/third-parties` is outside the stack, and the `worker` strategy is experimental, doesn't work in the App Router, and needs Partytown, which is outside the stack. |
| List virtualization | Long interactive lists, with approval | Over about 200 rows, with approval | Paginate on the server and try `content-visibility` first. The library is outside the stack (notes below). |
| Compressing JavaScript | CDN or proxy | CDN | 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.
- The LCP image and the critical font follow [b2c-b2b.md](b2c-b2b.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. Admin page sizes stop at 100, so a paginated table never reaches the virtualization threshold. Give each row of a long, mostly static list a functional utility from island's `styles/utilities.css`, `@utility content-auto-* { content-visibility: auto; contain-intrinsic-size: auto calc(var(--spacing) * --value(integer)); }`, used as `content-auto-16`: off-screen rows skip rendering but stay in the DOM, so find-in-page and screen readers keep working. When an interactive list still renders more than about 200 rows, such as a feed, a log, or a large tree, propose `@tanstack/react-virtual` with the reason and its gzipped size, and add it only after approval ([SKILL.md](../SKILL.md#2-stack)).
`packages/island/src/primitives/load-on-visible/LoadOnVisible.tsx`. It shows the fallback until the element comes within the root margin of the viewport, then renders the children inside `<Suspense>` with the same fallback. island also serves admin panels, so the primitive doesn't import `next/dynamic`: the caller passes the lazy component as children, and the import starts when the child first renders. A chunk that fails to load reaches the part's own error boundary.
```tsx
'use client';
import { Suspense, useEffect, useRef, useState } from 'react';
import { LOAD_ON_VISIBLE_ROOT_MARGIN } from './constants';
import type { LoadOnVisibleProps } from './types';
export function LoadOnVisible({ children, fallback, rootMargin = LOAD_ON_VISIBLE_ROOT_MARGIN }: LoadOnVisibleProps) {
const ref = useRef<HTMLDivElement>(null);
const [isNear, setIsNear] = useState(false);
useEffect(() => {
const element = ref.current;
if (isNear || !element) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) setIsNear(true);
},
{ rootMargin },
);
observer.observe(element);
return () => observer.disconnect();
}, [isNear, rootMargin]);
return <div ref={ref}>{isNear ? <Suspense fallback={fallback}>{children}</Suspense> : fallback}</div>;
}
```
The module also has `types.ts` (`LoadOnVisibleProps`: `children`, `fallback`, and an optional `rootMargin`), `constants.ts` (`LOAD_ON_VISIBLE_ROOT_MARGIN = '200px 0px'`), and `index.ts`. It has no `variants.ts`, because it has no styles.
`apps/<app>/src/app/(shop)/product/[id]/organisms/price-history/PriceHistory.tsx`. The product template, a Server Component, renders this client leaf below the fold. Call `next/dynamic` in the same client component as `LoadOnVisible`: a client component that a Server Component imports already ships with the route, so wrapping it would defer only its render. Leave out `ssr: false` here, as [b2c-b2b.md](b2c-b2b.md#data-flow) allows: `LoadOnVisible` or the interaction already keeps the child out of the server render, and with `ssr: false` `next/dynamic` adds its own `<Suspense>` with an empty fallback, which would replace the skeleton or the facade. Where the dynamic component renders unconditionally, keep `ssr: false` and pass `loading: () => <SameSizeSkeleton />`, so its boundary never renders blank. An admin caller passes a `React.lazy` component the same way.
```tsx
'use client';
import { LoadOnVisible } from '@project/island/primitives/load-on-visible';
import dynamic from 'next/dynamic';
import { PriceHistorySkeleton } from './components/price-history-skeleton';
import type { PriceHistoryProps } from './types';
const PriceHistoryChart = dynamic(() =>
import('./components/price-history-chart').then((mod) => mod.PriceHistoryChart),
);
export function PriceHistory({ productId }: PriceHistoryProps) {
return (
<LoadOnVisible fallback={<PriceHistorySkeleton />}>
<PriceHistoryChart productId={productId} />
</LoadOnVisible>
);
}
```
`apps/<app>/src/app/(shop)/product/[id]/organisms/product-video/ProductVideo.tsx`. One module-level function holds the import, so the facade's intent events (`pointerenter` and `focus`) start the download before the click, and the dynamic component reuses that download. The click sets state inside a transition: React keeps the facade on screen until the chunk arrives, and `isStarting` drives its loading state. The intent download ignores its own failure; the click retries through `next/dynamic`, and a failure there reaches the part's error boundary. A facade lives with its widget, in a route organism or, for a third-party embed such as chat, in the integration's `components/`. An admin panel builds the component with `lazy(() => loadPdfViewer().then((mod) => ({ default: mod.PdfViewer })))`.
```tsx
'use client';
import dynamic from 'next/dynamic';
import { useState, useTransition } from 'react';
import { useTranslation } from 'react-i18next';
import { VideoFacade } from './components/video-facade';
import type { ProductVideoProps } from './types';
const loadVideoPlayer = () => import('./components/video-player');
const VideoPlayer = dynamic(() => loadVideoPlayer().then((mod) => mod.VideoPlayer));
export function ProductVideo({ video }: ProductVideoProps) {
const { t } = useTranslation('catalog');
const [isPlaying, setIsPlaying] = useState(false);
const [isStarting, startTransition] = useTransition();
if (isPlaying) return <VideoPlayer src={video.url} autoPlay />;
return (
<VideoFacade
posterUrl={video.posterUrl}
label={t('product.video.play', { name: video.title })}
isLoading={isStarting}
onIntent={() => {
loadVideoPlayer().catch(() => undefined);
}}
onPlay={() => startTransition(() => setIsPlaying(true))}
/>
);
}
```
## 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).
B2C/B2B (data details 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 `<Suspense>` 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`.
Admin panel ([admin-panels.md](admin-panels.md#lazy-loading)); anything not listed loads with its screen:
1. A route → `lazyRouteComponent` in `navigation/navigation.ts`, with a skeleton of the page layout as `pendingComponent`.
2. A heavy widget, such as a chart, an editor, a PDF viewer, or a map → a `React.lazy` component. Below the fold, pass it to `LoadOnVisible` with a same-size skeleton as `fallback`; `LoadOnVisible` supplies the Suspense boundary. Above the fold, wrap it in its own `<Suspense>` with that skeleton. Either way, it gets its own error boundary.
3. Tab or modal content → its lazy component renders on first open. Build that into island's tabs and dialog organisms, and keep a visited tab mounted in `<Activity mode="hidden">` so it keeps its state when the user switches away.
4. Select or autocomplete options → the part model's `useQuery` with `enabled: isOpen`, searched and paginated on the server.

View File

@ -0,0 +1,69 @@
# Spec Kit
Projects use [Spec Kit](https://github.com/github/spec-kit) for spec-driven development. In Claude Code it installs as the `speckit-*` skills (`specify init` with `--integration claude` puts them in `.claude/skills/`), invoked as `/speckit-*`.
- Constitution: `.specify/memory/constitution.md`.
- Feature artifacts: `specs/<###-feature>/`, holding `spec.md`, `plan.md`, `research.md`, `data-model.md`, `contracts/`, `quickstart.md`, `tasks.md`, and `checklists/`.
- The active feature is recorded in `.specify/feature.json`.
The speckit skills run the process; this skill supplies the front-end architecture inside each artifact. If `.specify/` is missing, suggest initializing Spec Kit before a large feature. For a small change, follow the workflow in SKILL.md and put the plan in the PR description.
## Constitution (once per repo)
Propose these principles, adapted to the repo's project type:
```text
/speckit-constitution Front-end principles for this Nx monorepo (<B2C/B2B | admin panel>):
1. Structure: follow the front-end-architect skill's project structure. Code lives in src/. Files and folders are kebab-case; component files are PascalCase.
2. Layers: features are DDD (entities, repositories, caches on B2C/B2B, actions, models). Actions emit their event when they succeed. Each feature has its own HTTP client in http.ts, extended from the root client, and repositories send requests only through it. Repositories have no client-side dependencies. UI and stores use *Payload types only. No upward or cross-product imports; ESLint boundaries must pass.
3. Exports: tree-shakeable named re-exports, never export *. Every module is importable by subpath. B2C/B2B projects expose server-only code through server.ts.
4. UX: every screen has loading, empty, error, and in-progress states. Every completed action shows feedback. Every error says how to fix it. All text is translatable. WCAG 2.1 AA.
5. Performance: B2C/B2B routes meet p75 LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1 and their JS budgets. Admin screens never flicker, lazy-load routes and heavy widgets, and virtualize long lists.
6. Rendering (B2C/B2B): every request renders a fresh page; the Next.js server keeps no cache between requests.
7. Access (admin): every page, action, and navigation item declares its permission.
8. Testing: every feature ships Playwright specs for the happy path, validation error, and server error, plus inspected screenshots.
9. Stack: no dependency outside the agreed stack without an approved justification.
```
## Per feature
| Step | What you add |
|---|---|
| `/speckit-specify` | Keep the spec free of technology. Make sure it states who uses the feature and how often, and every state (empty, loading, error, in progress). B2C/B2B: device views, SEO needs, signed-in versus signed-out behavior, expected traffic. Admin: roles and permissions per page and action, the business domains involved, and which actions need help text. |
| `/speckit-clarify` | Focus on permissions, error cases, pagination and filters, mobile versus desktop differences, how fresh data must be, and SEO. |
| `/speckit-plan` | Pass the project type, stack, and affected projects (template below), then check that `plan.md` contains everything listed under Plan contents. |
| `/speckit-checklist` | Focus on "UX states and copy", plus "access levels" (admin) or "performance and SEO" (B2C/B2B). |
| `/speckit-tasks` | Check that the tasks follow the Task order below. |
| `/speckit-analyze` | Check that plan paths match project-structure.md, that every requirement has its states and tests, that no task breaks a boundary, and that no task uses a pattern from the "Not used here" list in design-patterns.md. |
| `/speckit-implement` | Follow SKILL.md and code-patterns.md. Read design-patterns.md before you add a pattern the plan names or a task calls for. When code resists a task, refactor it first, in its own commit (refactoring.md). After each user story, run lint, type-check, and tests for the affected projects. |
| `/speckit-converge` | Run the Definition of Done from SKILL.md and the playbook, and repeat implement and converge until it reports Converged. |
Plan argument template:
```text
/speckit-plan Project type: <B2C/B2B | admin panel>. Stack: Nx, <Next.js App Router | React + TanStack Router>, Tailwind CSS v4 with cva, valibot, react-hook-form, zustand + immer, TanStack Query, i18next, sonner, Playwright. Follow the front-end-architect skill for structure, layers, exports, and budgets. Affected projects: <apps/..., platforms/..., packages/...>.
```
## Plan contents
- Technical Context: the project type and stack.
- Constitution Check: each principle, marked as passing or as a justified violation.
- Project Structure: exact paths in this skill's layout, covering routes or screens, templates and organisms, feature layers (entities, repositories, caches on B2C/B2B, actions, page and part models), stores, validations, and the island components to add or extend.
- `research.md`: decisions and their trade-offs, such as each route's streamed parts and how each client part gets its server data (B2C/B2B), lazy-loading boundaries and what triggers each deferred part ([rendering-patterns.md](rendering-patterns.md)), each new non-obvious pattern with its signal and the simpler option you rejected ([design-patterns.md](design-patterns.md)), and any new dependency.
- `data-model.md`: entities, the `*Args`, `*Dto`, `*ResponseDto`, and `*Payload` types for each endpoint, stores, and query keys.
- `contracts/`: each endpoint's method, path, DTOs, error codes, and pagination and filter parameters.
- `quickstart.md`: the Playwright scenarios that prove the feature works.
- B2C/B2B: the JS budget and web-vitals targets for each route. Admin: the permission matrix of roles against pages and actions.
## Task order
1. Setup: Nx projects, tags, subpath exports, and new env variables (the app's env schemas and each project's env type).
2. Foundational: entities, repositories with mappers and query keys, caches (B2C/B2B), island components or variants.
3. Each user story: actions, then models, then templates and organisms, then the route or screen entry, then its Playwright spec.
4. Polish: screenshot inspection at every viewport, accessibility, the bundle and web-vitals check (B2C/B2B), and help content (admin).
Mark tasks that touch separate files with `[P]` so they can run in parallel.
## Bugs
If the repo has Spec Kit's bug extension, run `/speckit-bug-assess`, then `/speckit-bug-fix`, then `/speckit-bug-test`. Fix the fault in the layer that owns it (repository, mapper, action, model, or component) instead of patching the symptom in the UI.

9
.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
.nx/installation
.nx/cache
.nx/workspace-data
.nx/self-healing
.nx/migrate-runs
.nx/polygraph
.claude/worktrees
.claude/settings.local.json

122
.nx/nxw.js Normal file
View File

@ -0,0 +1,122 @@
"use strict";
// This file should be committed to your repository! It wraps Nx and ensures
// that your local installation matches nx.json.
// See: https://nx.dev/recipes/installation/install-non-javascript for more info.
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require('fs');
const path = require('path');
const cp = require('child_process');
const installationPath = path.join(__dirname, 'installation', 'package.json');
function matchesCurrentNxInstall(currentInstallation, nxJsonInstallation) {
if (!currentInstallation.devDependencies ||
!Object.keys(currentInstallation.devDependencies).length) {
return false;
}
try {
if (currentInstallation.devDependencies['nx'] !==
nxJsonInstallation.version ||
require(path.join(path.dirname(installationPath), 'node_modules', 'nx', 'package.json')).version !== nxJsonInstallation.version) {
return false;
}
for (const [plugin, desiredVersion] of Object.entries(nxJsonInstallation.plugins || {})) {
if (currentInstallation.devDependencies[plugin] !== desiredVersion) {
return false;
}
}
return true;
}
catch {
return false;
}
}
function ensureDir(p) {
if (!fs.existsSync(p)) {
fs.mkdirSync(p, { recursive: true });
}
}
function getCurrentInstallation() {
try {
return require(installationPath);
}
catch {
return {
name: 'nx-installation',
version: '0.0.0',
devDependencies: {},
};
}
}
function performInstallation(currentInstallation, nxJson) {
fs.writeFileSync(installationPath, JSON.stringify({
name: 'nx-installation',
devDependencies: {
nx: nxJson.installation.version,
...nxJson.installation.plugins,
},
}));
try {
// --include=dev forces install even if consumer env sets NODE_ENV=production / omit=dev.
cp.execSync('npm i --include=dev', {
cwd: path.dirname(installationPath),
stdio: 'inherit',
windowsHide: true,
});
}
catch (e) {
// revert possible changes to the current installation
fs.writeFileSync(installationPath, JSON.stringify(currentInstallation));
// rethrow
throw e;
}
}
function ensureUpToDateInstallation() {
const nxJsonPath = path.join(__dirname, '..', 'nx.json');
let nxJson;
try {
nxJson = require(nxJsonPath);
if (!nxJson.installation) {
console.error('[NX]: The "installation" entry in the "nx.json" file is required when running the nx wrapper. See https://nx.dev/recipes/installation/install-non-javascript');
process.exit(1);
}
}
catch (e) {
if (e instanceof Error &&
e.code === 'MODULE_NOT_FOUND') {
console.error('[NX]: The "nx.json" file is required when running the nx wrapper. See https://nx.dev/recipes/installation/install-non-javascript');
}
else {
console.error(`[NX]: Failed to parse "nx.json": ${e instanceof Error ? e.message : e}. See https://nx.dev/recipes/installation/install-non-javascript`);
}
process.exit(1);
}
try {
ensureDir(path.join(__dirname, 'installation'));
const currentInstallation = getCurrentInstallation();
if (!matchesCurrentNxInstall(currentInstallation, nxJson.installation)) {
performInstallation(currentInstallation, nxJson);
}
}
catch (e) {
const messageLines = [
'[NX]: Nx wrapper failed to synchronize installation.',
];
if (e instanceof Error) {
messageLines.push('');
messageLines.push(e.message);
messageLines.push(e.stack);
}
else {
messageLines.push(e.toString());
}
console.error(messageLines.join('\n'));
process.exit(1);
}
}
if (!process.env.NX_WRAPPER_SKIP_INSTALL) {
ensureUpToDateInstallation();
}
require('./installation/node_modules/nx/dist/bin/nx');

24
CLAUDE.md Normal file
View File

@ -0,0 +1,24 @@
<!-- nx configuration start-->
<!-- Leave the start & end comments to automatically receive updates. -->
# General Guidelines for working with Nx
- For navigating/exploring the workspace, invoke the `nx-workspace` skill first - it has patterns for querying projects, targets, and dependencies
- When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task through `nx` (i.e. `nx run`, `nx run-many`, `nx affected`) instead of using the underlying tooling directly
- Prefix nx commands with the workspace's package manager (e.g., `pnpm nx build`, `npm exec nx test`) - avoids using globally installed CLI
- You have access to the Nx MCP server and its tools, use them to help the user
- For Nx plugin best practices, check `node_modules/@nx/<plugin>/PLUGIN.md`. Not all plugins have this file - proceed without it if unavailable.
- NEVER guess CLI flags - always check nx_docs or `--help` first when unsure
## Scaffolding & Generators
- For scaffolding tasks (creating apps, libs, project structure, setup), ALWAYS invoke the `nx-generate` skill FIRST before exploring or calling MCP tools
## When to use nx_docs
- USE for: advanced config options, unfamiliar flags, migration guides, plugin configuration, edge cases
- DON'T USE for: basic generator syntax (`nx g @nx/react:app`), standard commands, things you already know
- The `nx-generate` skill handles generator discovery internally - don't call nx_docs just to look up generator syntax
<!-- nx configuration end-->

5
nx Executable file
View File

@ -0,0 +1,5 @@
#!/bin/bash
command -v node >/dev/null 2>&1 || { echo >&2 "Nx requires NodeJS to be available. To install NodeJS and NPM, see: https://nodejs.org/en/download/ ."; exit 1; }
command -v npm >/dev/null 2>&1 || { echo >&2 "Nx requires npm to be available. To install NodeJS and NPM, see: https://nodejs.org/en/download/ ."; exit 1; }
path_to_root=$(dirname $BASH_SOURCE)
node $path_to_root/.nx/nxw.js "$@"

10
nx.bat Normal file
View File

@ -0,0 +1,10 @@
@ECHO OFF
SETLOCAL
SET path_to_root=%~dp0
WHERE node >nul 2>nul
IF %ERRORLEVEL% NEQ 0 (ECHO Nx requires NodeJS to be available. To install NodeJS and NPM, see: https://nodejs.org/en/download/ . & GOTO exit)
WHERE npm >nul 2>nul
IF %ERRORLEVEL% NEQ 0 (ECHO Nx requires npm to be available. To install NodeJS and NPM, see: https://nodejs.org/en/download/ . & GOTO exit)
node %path_to_root%\.nx\nxw.js %*
:exit
cmd /c exit /b %ERRORLEVEL%

7
nx.json Normal file
View File

@ -0,0 +1,7 @@
{
"installation": {
"version": "23.2.1"
},
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"analytics": false
}