Communityコーディング&開発github.com

frontend-architecture

Structure and data rules for a feature-sliced Next.js App Router app: feature slices, a shared ApiClient with feature API factories, auth and session, server/client boundaries, and state and data fetching with Redux Toolkit and RTK Query. Use when editing production source under src/app, src/features or src/shared. Not for tests (frontend-testing) or SEO markup (frontend-seo).

frontend-architecture とは?

frontend-architecture is a Claude Code agent skill that structure and data rules for a feature-sliced Next.js App Router app: feature slices, a shared ApiClient with feature API factories, auth and session, server/client boundaries, and state and data fetching with Redux Toolkit and RTK Query. Use when editing production source under src/app, src/features or src/shared. Not for tests (frontend-testing) or SEO markup (frontend-seo).

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/19mittal/dotnet-next-toolkit/tree/HEAD/plugins/nextjs-frontend/skills/frontend-architecture

Installed? Explore more コーディング&開発 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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/.

TaskApply?
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.

ConcernContract
Backendan HTTP API under a versioned base such as /api/v1
JSONcamelCase properties; enums as strings
ErrorsRFC 9457 ProblemDetails → ApiError
Base URLone 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
SliceOwnsForbidden
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 exportfetch 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 raw fetch in features or app/.
  • The client attaches the credential itself (§4); call sites never build an Authorization header.
  • 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.ts and 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.

ModelWhere the credential livesOn 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 expectsThe session is gone: raise one "unauthenticated" signal and navigate to sign-in. There is no refresh to invent
Bearer access + refresh tokensAccess 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 themThe client refreshes once behind a mutex and retries; a failed refresh clears the session and navigates to sign-in
PieceRole
AuthService (features/Auth/model)Orchestrates sign-in → establish session → load the current user; sign-out revokes server-side
useAuthClient 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 → ToRule
app/ → features/Import only from @/features/<Domain> barrel (index.ts)
features/ → shared/✅
features/A → features/BOnly 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.

ConcernRule
Server stateOne 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
ThunkscreateAsyncThunk only for multi-step client orchestration; signal and rejectWithValue required
Client statecreateSlice only for synchronous shared UI state; never API data, never hand-written loading/error flags
TypingExplicit types for every request, response and DTO (generated from the contract where possible); no any; typed hooks only
ErrorsA wrapped base query handles 401 per §4 and returns serialisable errors; an Error Boundary around each independent feature module
FormsUnsubmitted inputs and validation errors in local state or a form library — never Redux
PerformancecreateSelector / selectFromResult for derived data; next/dynamic for heavy client components; measure first
SecurityNEXT_PUBLIC_* is public; server secrets behind server-only; no secrets, tokens or PII in the store
SSR isolationPer-request makeStore() held by a Client Component StoreProvider; never a module-level store
RenderingIndependent 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 onRead
Deciding where a piece of state lives; Context; slices; form statereference/state-placement.md
An RTK Query endpoint, cache tags, the per-request store, the 401 wrapper, a thunkreference/rtk-query.md
DTO typing, selectors, bundle size, env and secret boundariesreference/typing-performance-security.md
Server/client boundaries, waterfalls, mutations and caching in the App Router; reviewing for smellsreference/app-router-and-detection.md

Checklist

  • HTTP via ApiClient + createXxxApi(client) factory in the owning feature
  • DTOs updated in shared/types/api.ts when backend contracts change
  • Business logic in features/<Domain>/model/ or api/ — not in app/
  • Barrel index.ts is 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), not useEffect+useState
  • The Redux store is created per request (makeStore in a Client StoreProvider), 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

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

関連スキル