Frontend Architecture
0. Project context
Resolve once per session, from the working directory: the app root <frontend-root> (the nearest
package.json that depends on next — ask if several match). Every path below is relative to it.
Read the package name and real library versions from that package.json; where they differ from
what this skill describes, the repo wins. Take product names from the repo — never invent one.
ApiClient, getApiClient, createTestApiClient and apiPath are this skill's names for the shared
HTTP layer. Use the app's existing equivalents under their own names; create them only if the app has
no shared HTTP client.
When to Apply
Apply only for production source under src/app/, src/features/, or src/shared/.
| Task | Apply? |
|---|---|
| New feature API module, hook, model, or barrel | ✅ |
ApiClient, session handling, shared types | ✅ |
| App Router page/layout shell (composition only) | ✅ |
| Fetching, caching, mutating or sharing state (hook, provider, store, Server Action) | ✅ → §7 |
| Unit/integration tests | ❌ → use frontend-testing |
| Public page SEO (metadata, sitemap, semantic HTML) | ❌ → use frontend-seo |
Error boundaries, error.tsx, failure UX, server validation on forms | ❌ → use error-handling-frontend |
1. Stack & Backend Contract
Written against Next.js 16 (App Router), React 19 and strict TypeScript. Check the installed versions —
App Router APIs change between majors, so confirm an API in node_modules/next/dist/docs before
relying on it.
| Concern | Contract |
|---|---|
| Backend | an HTTP API under a versioned base such as /api/v1 |
| JSON | camelCase properties; enums as strings |
| Errors | RFC 9457 ProblemDetails → ApiError |
| Base URL | one env value (NEXT_PUBLIC_API_BASE_URL; default in .env.example), joined by one helper (apiPath('auth/login') → /api/v1/auth/login) |
2. Feature-Sliced Design
Business logic lives in src/features/<Domain>/:
features/
Auth/
__tests__/ ← feature-wide tests (useAuth, authService, …)
api/auth-api.ts ← createAuthApi(client)
model/auth-service.ts ← session orchestration (login, logout, loadCurrentUser)
hooks/useAuth.ts ← 'use client' — React state wrapper
index.ts ← public barrel
<Domain>/ ← one folder per domain; resolve the real set from src/features/
__tests__/ ← *Service.test.ts, use*.test.ts, *-api.test.ts
api/ hooks/ model/
index.ts
shared/
config/env.ts
lib/api-client.ts ← fetch + credential + one 401 recovery
lib/api-client-factory.ts ← getApiClient() singleton, createTestApiClient()
lib/token-storage.ts ← credential holder injected into the client (§4)
lib/api-error.ts
types/api.ts ← mirrors the backend's request/response DTOs
app/ ← routes, layouts, metadata — no business logic
| Slice | Owns | Forbidden |
|---|---|---|
features/<Domain> | api/, model/, hooks/, components/ | Imports from src/app/ |
shared/ | Cross-cutting infra (HTTP, env, DTO types) | Domain rules, feature API calls |
app/ | Route segments, layout composition, metadata export | fetch to backend, validation, domain state |
Adding a domain means adding a folder with the layout above plus a barrel — nothing registers it centrally.
3. API Client Pattern
Every feature exposes a factory — never a global fetch wrapper per call site:
// ✅ CORRECT — feature API factory
export function createAuthApi(client: ApiClient) {
return {
login(request: LoginRequest): Promise<LoginResponse> {
return client.request(apiPath('auth/login'), {
method: 'POST',
body: request,
anonymous: true,
skipRefresh: true,
});
},
};
}
// ✅ CORRECT — consumer uses singleton
import { getApiClient } from '@/shared/lib/api-client-factory';
import { createOrdersApi } from '@/features/Orders'; // domain name is illustrative
const orders = createOrdersApi(getApiClient());
Rules:
- All HTTP goes through
ApiClient.request()— no rawfetchin features orapp/. - The client attaches the credential itself (§4); call sites never build an
Authorizationheader. - Sign-in and refresh calls are
anonymous: true+skipRefresh: true. - A 401 is recovered at most once, inside the client (§4). No call site adds a second retry.
- DTO changes start in
src/shared/types/api.tsand stay aligned with the backend's DTOs. - Tests build their own client with injected dependencies — never
getApiClient()in tests. - Non-2xx becomes
ApiError(status,code,traceId,fieldErrors). What call sites do with it — field mapping, error routes, retry, the status→UX map — is [[error-handling-frontend]]. - Cross-cutting per-request headers (a captcha token, a correlation id) are added by an interceptor registered on the client, never at call sites. Read reference/api-client-interceptors.md before adding one.
4. Auth & Session
Use the auth model the backend provides. Find it first — read the sign-in endpoint's response and the existing session code — and do not introduce a second one.
| Model | Where the credential lives | On 401 |
|---|---|---|
| Server session in an httpOnly cookie (preferred for a browser app) | An httpOnly, Secure, SameSite cookie; JavaScript never reads it. Requests send credentials, and mutations carry whatever CSRF token the backend expects | The session is gone: raise one "unauthenticated" signal and navigate to sign-in. There is no refresh to invent |
| Bearer access + refresh tokens | Access token in memory only; refresh token in an httpOnly cookie where the backend allows it. Never localStorage or sessionStorage — any script on the page can read them | The client refreshes once behind a mutex and retries; a failed refresh clears the session and navigates to sign-in |
| Piece | Role |
|---|---|
AuthService (features/Auth/model) | Orchestrates sign-in → establish session → load the current user; sign-out revokes server-side |
useAuth | Client hook exposing user, login, logout, isLoading |
Credential holder (shared/lib/token-storage.ts) | Injected into the client so tests can swap an in-memory one; unnecessary for cookie sessions |
// ✅ CORRECT — page composes; hook lives in feature
import { useAuth } from '@/features/Auth';
// ❌ FORBIDDEN — login fetch in app route
export default function Page() {
const res = await fetch(`${process.env.API}/auth/login`, ...);
}
5. Next.js App Router — Server vs Client
Pages and layouts are Server Components unless interactivity requires otherwise. 'use client' goes on
the smallest leaf that needs state, effects, handlers or a browser API — in src/features/**/hooks/
and components/, never at the root of a public src/app/**/page.tsx. A layout or page marked
'use client' pulls its whole import graph into the bundle.
app/page.tsx (Server)
└── Dashboard (Server)
└── OrderForm ('use client' in features/<Domain>/components/)
Pass serializable props Server → Client. Co-locate interactive UI in the owning feature slice.
6. Dependency Flow
src/app → src/features → src/shared
| From → To | Rule |
|---|---|
app/ → features/ | Import only from @/features/<Domain> barrel (index.ts) |
features/ → shared/ | ✅ |
features/A → features/B | Only via B's index.ts; no circular imports |
features/ → app/ | ❌ Never |
shared/ → features/ | ❌ Never |
// ✅ import { useAuth } from '@/features/Auth';
// ❌ import { useAuth } from '@/features/Auth/hooks/useAuth';
7. State, data fetching, typing and rendering
Default stack: Redux Toolkit (client state) + RTK Query (the sole server-state store) + custom
createAsyncThunk only for multi-step orchestration. If the app already uses another server-state
library (TanStack Query, SWR), keep it — never run two for the same job — and apply the placement,
typing and App Router rules below while skipping the RTK-specific ones.
| Concern | Rule |
|---|---|
| Server state | One server-state store: one createApi, features add endpoints with injectEndpoints; tags declared once. Never useEffect+useState, Context, a slice or a thunk for API data |
| Thunks | createAsyncThunk only for multi-step client orchestration; signal and rejectWithValue required |
| Client state | createSlice only for synchronous shared UI state; never API data, never hand-written loading/error flags |
| Typing | Explicit types for every request, response and DTO (generated from the contract where possible); no any; typed hooks only |
| Errors | A wrapped base query handles 401 per §4 and returns serialisable errors; an Error Boundary around each independent feature module |
| Forms | Unsubmitted inputs and validation errors in local state or a form library — never Redux |
| Performance | createSelector / selectFromResult for derived data; next/dynamic for heavy client components; measure first |
| Security | NEXT_PUBLIC_* is public; server secrets behind server-only; no secrets, tokens or PII in the store |
| SSR isolation | Per-request makeStore() held by a Client Component StoreProvider; never a module-level store |
| Rendering | Independent reads in parallel; slow sections behind <Suspense> / loading.tsx; each write names its revalidation path |
The table is the summary. Load the reference that matches the task — one, not all four:
| Working on | Read |
|---|---|
| Deciding where a piece of state lives; Context; slices; form state | reference/state-placement.md |
| An RTK Query endpoint, cache tags, the per-request store, the 401 wrapper, a thunk | reference/rtk-query.md |
| DTO typing, selectors, bundle size, env and secret boundaries | reference/typing-performance-security.md |
| Server/client boundaries, waterfalls, mutations and caching in the App Router; reviewing for smells | reference/app-router-and-detection.md |
Checklist
- HTTP via
ApiClient+createXxxApi(client)factory in the owning feature - DTOs updated in
shared/types/api.tswhen backend contracts change - Business logic in
features/<Domain>/model/orapi/— not inapp/ - Barrel
index.tsis the only public entry for cross-layer imports -
'use client'isolated to hooks/components inside features, on the smallest leaf - No credential in
localStorage/sessionStorage; 401 recovered once, inside the client - Client fetches go through the server-state store with tags (or a Server Component
await), notuseEffect+useState - The Redux store is created per request (
makeStorein a ClientStoreProvider), never a module singleton - Every request/response/DTO has an explicit type; no
any; no API data or loading flags in slices - No waterfalls;
loading.tsx/error.tsx/<Suspense>where data is async - Each write has one stated path and invalidates/revalidates what it changed