149 lines
17 KiB
Markdown
149 lines
17 KiB
Markdown
# 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 · Errors · State and auth · Bundle and code splitting · Hydration and navigation · Responsiveness and monitoring · Example: caches, page, and parts · Definition of Done
|
||
|
||
## Targets
|
||
|
||
These are defaults; tighten them per product in the plan.
|
||
|
||
| Metric | Target |
|
||
|---|---|
|
||
| LCP, p75 of mobile field data | ≤ 2.5 s |
|
||
| INP, p75 | ≤ 200 ms |
|
||
| CLS, p75 | ≤ 0.1 |
|
||
| TTFB, p75 | ≤ 0.8 s |
|
||
| First-load JS per route, gzipped, framework included | ≤ 200 KB |
|
||
| Route-specific client JS, gzipped | ≤ 100 KB |
|
||
|
||
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)).
|
||
- 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.
|
||
- The server render never depends on auth: every visitor of a URL gets the same server HTML. A page or part whose UI depends on the viewer (it needs a logged-in user, differs for guests, members, and paying members, or shows the viewer's own data) renders completely in the browser behind a same-size skeleton. What is the same for every visitor renders on the server. An explicit request from the developer overrides either default ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
|
||
- Templates stay Server Components. Interactive parts are small client components, each driven by its part model (`use-<page>-<part>-part.ts`). Don't turn a whole template into a client component to use a page model when only part of it is interactive.
|
||
- Keep props passed to client components small and serializable; they are serialized into the page's RSC payload.
|
||
- Pages are thin entrypoints. The page resolves the device on the server and renders the mobile or the desktop template. Only that view's client code ships, the markup matches on hydration, and nothing shifts. Never choose between layouts with viewport checks in components.
|
||
- Stream: add `loading.tsx` per route group and `<Suspense>` with same-size skeletons around slow parts, each inside its own `PartBoundary`. One slow or failing backend call must never block the whole page. Record each route's streamed and auth-dependent parts in the plan.
|
||
- 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, keep nothing afterwards, and never depend on who the viewer is.
|
||
|
||
1. Every root layout imports `bootstrap.server.ts` first.
|
||
2. The page resolves the device, awaits only what the first paint needs through caches or a server page loader, and renders the mobile or the desktop template.
|
||
3. Server components that need more data read it through caches. A slow part is an async server component inside `<Suspense>` with a same-size skeleton, so the page streams around it. An auth-dependent part renders only its skeleton on the server.
|
||
4. Client components get server data as props or through query hydration (below). In the browser their models take over: queries through repositories, mutations through actions, and auth-dependent parts render their variant once the auth store knows the viewer. After a mutation that changes server-rendered content, `router.refresh()` renders the page again.
|
||
|
||
**Caches** (`features/<feature>/caches/`, server-only)
|
||
|
||
- Each cache is React's `cache()` around one repository call: `export const getProduct = cache((id: string) => productsRepository.get({ id }))`. React keeps the result for the current request only, so it's an allowed server cache (see No server cache).
|
||
- On the server, pages, loaders, `generateMetadata`, and server components read data only through caches, never through a repository directly. That's why ten components that need the same product send one request.
|
||
- Cache arguments are primitives, such as ids and page numbers. React compares arguments by identity, so `getProducts({ page })` would miss every time.
|
||
- Define caches at module level. A `cache()` created inside a component is new on every render.
|
||
- The module's entry is `server.ts`, with no `index.ts`, and the platform's `server.ts` re-exports it.
|
||
|
||
**Handing server data to client components**
|
||
|
||
- Props, for data the client part only shows or starts from: pass the `*Payload`, small and serializable. To stream it, pass the un-awaited promise and read it with `use()` inside `<Suspense>`.
|
||
- Query hydration, for data the client part keeps live (refetches, pagination, filters, or mutations that update it): prefetch into a `QueryClient` from `getQueryClient()` in `configs/react-query.ts`, with the cache as the `queryFn`, and render the part inside `<HydrationBoundary state={dehydrate(queryClient)}>`. The part's model queries the same key and starts with the data.
|
||
- An awaited prefetch puts the data in the HTML. 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 depends on the viewer, is below the fold, or is shown on interaction, through a part model inside `<Suspense>` with a skeleton.
|
||
- A browser-only part uses `useQuery` and shows its skeleton while pending, or is loaded with `next/dynamic` from a client component: with `ssr: false` and a same-size `loading` skeleton when it renders at once, and without `ssr: false` when `LoadOnVisible` or an interaction already delays it ([rendering-patterns.md](rendering-patterns.md)). `useSuspenseQuery` is only for queries the server prefetched: any other query would run during SSR, where requests carry none of the user's cookies.
|
||
|
||
## Errors
|
||
|
||
The model, the boundaries, and their code are in [error-handling.md](error-handling.md). What is special here:
|
||
|
||
- Server reads classify on the server, because a Server Component error reaches the browser with only its digest. Pages and server parts read through `readOnServer`: the page calls `notFound()` for 404 and 410, renders the `no-access` empty state for 403 with `robots: { index: false }`; a part renders its empty state for 404 and 403. Everything else is rethrown to a boundary.
|
||
- Boundaries: `app/global-error.tsx` is EB-W; every route group has `error.tsx` (page EB-S) and, when it calls `notFound()`, `not-found.tsx`; each part has a `PartBoundary` built with `catchError`, which lets `notFound()` and `redirect()` through. Error pages render `noindex`.
|
||
- A part that must show an empty state awaits its read on the server; an un-awaited prefetch fits only reads that can't answer 404 or 403.
|
||
- `instrumentation.ts` configures the error handler for the server and reports what no server code caught; `bootstrap.client.ts` configures it for the browser.
|
||
|
||
## State and auth
|
||
|
||
- `configs/react-query.ts`: `getQueryClient()` returns a new `QueryClient` on every server call and one shared instance in the browser. `staleTime` is above zero (60 s) so hydrated data isn't refetched on mount, queries don't retry (the HTTP lib does), a failed first load throws to its boundary while a failed refetch keeps the data, and pending queries are dehydrated so they can stream.
|
||
- zustand stores hold client state only. Never write to a store during server render: on the server a module-level store is shared by every request, so one user's data would leak to another. Pass server data through props or the query cache. If a store must start from server data, create it per request with `createStore` inside a provider.
|
||
- Server-side requests forward only the incoming request's cookies that the render needs, such as locale and theme, and never the auth cookies. Configure the HTTP lib once in `bootstrap.server.ts` with `configureServerHttp`: the server `baseUrl` from the app's server env, and a cookie provider that calls `cookies()` from `next/headers` on each request and keeps only the app's forwarded cookie names ([lib-http.md](lib-http.md#server-side)). That configures the root client, so every feature client forwards the same cookies. Never keep a user's cookies in module state.
|
||
- On the server, the HTTP lib never refreshes, never calls `abortAll`, and retries at most once with a shorter timeout, so a slow back end doesn't hold up rendering (see [lib-http.md](lib-http.md#server-side)).
|
||
- The server never reads or refreshes the session. The browser learns who the viewer is once per load through the auth store's `status`, and the browser's HTTP lib refreshes an expired session on a 401 ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
|
||
- The `cookie` and `storage` libs are browser-only. Never read them during render: client components also render on the server, and the value would differ between server and browser. A value the page needs while rendering (theme, locale) is read on the server with `cookies()` and passed down as a prop.
|
||
- Persisted zustand stores set `skipHydration: true` and rehydrate in an effect of the platform's `AppShell`, so the first browser render matches the server's (code in code-patterns.md, Persisted store).
|
||
|
||
## 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)).
|
||
|
||
## Responsiveness and monitoring
|
||
|
||
- Each route has a mobile and a desktop template, and each template stays fluid across its device range. Touch targets are at least 44×44 px on mobile.
|
||
- Report field web vitals per route (`useReportWebVitals` into the analytics integration), report errors through the error handler to the Sentry integration (`instrumentation.ts` on the server, `bootstrap.client.ts` in the browser), and review p75 per release.
|
||
|
||
## Example: caches, page, and parts
|
||
|
||
|
||
In [page-example.md](page-example.md). Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet.
|
||
|
||
## 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
|
||
[ ] global-error.tsx, error.tsx in every route group, and not-found.tsx where notFound() is called; error pages are noindex
|
||
[ ] Server reads that can answer 404 or 403 go through readOnServer; every streamed part has a PartBoundary
|
||
[ ] Each route's streamed parts are decided and written in the plan
|
||
[ ] The server render is the same for every visitor: no session reads, no auth cookies forwarded, no variant picked on the server; auth-dependent parts render their skeleton until the browser knows the viewer, unless the developer asked otherwise
|
||
[ ] Page is a thin entrypoint that renders the server-chosen mobile or desktop template
|
||
[ ] 'use client' only on interactive leaves; no server-only code reachable from client bundles
|
||
[ ] New server-only code is exported through server.ts and starts with import 'server-only'
|
||
[ ] 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
|
||
```
|