Community程式設計與開發github.com

nextjs-standards

Baseline React, Next.js App Router and TypeScript standards for an app that is NOT feature-sliced: server vs client components, data fetching, state, forms, performance, accessibility, security. Do not load when the app has src/features slices over a shared ApiClient — use frontend-registry there.

nextjs-standards 是什麼?

nextjs-standards is a Claude Code agent skill that baseline React, Next.js App Router and TypeScript standards for an app that is NOT feature-sliced: server vs client components, data fetching, state, forms, performance, accessibility, security. Do not load when the app has src/features slices over a shared ApiClient — use frontend-registry there.

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/19mittal/dotnet-next-toolkit/tree/HEAD/plugins/nextjs-frontend/skills/nextjs-standards

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

React / Next.js standards (baseline)

Precedence. This is the fallback for an app that is not organised as feature slices. Where the app has src/features/<Domain> slices over a shared ApiClient, route through frontend-registry — frontend-architecture, frontend-design-system, frontend-seo, and frontend-testing are authoritative there and define the FSD layout, ApiClient, styling system, and test setup. Use this skill only for the general correctness rules below that those skills do not cover. A repo's own skills and CLAUDE.md outrank both sets.

Otherwise: project conventions win. Check next.config, tsconfig.json, ESLint config, and existing components first. Do not introduce a second state library, styling approach, or data-fetching pattern alongside one that already exists — in particular, do not reach for Tailwind in a project built on CSS variables and component classes.

TypeScript

  • strict: true. No any — use unknown plus narrowing, or a real type. as casts need a reason.
  • Type props explicitly; don't rely on inference across a module boundary.
  • Discriminated unions over optional-flag soup: type State = {status:'idle'} | {status:'loading'} | {status:'error', error:Error} | {status:'ok', data:T}.
  • Validate anything crossing a trust boundary (API responses, searchParams, form data, env) with Zod — a TS type is a compile-time claim, not a runtime guarantee.

Server vs Client components (App Router)

This is the decision that most often goes wrong. Default is Server Component.

  • Add 'use client' only for: event handlers, useState/useEffect/useReducer, browser APIs, or a client-only library. Push it to the leaf, not the page/layout.
  • A client component cannot import a server component as a child, but it can accept one via children/props — use that to keep providers thin.
  • Never import server-only code (DB client, secrets, API keys) into a module reachable from a client component. Mark such modules import 'server-only'.
  • Fetch data in server components with await directly. Do not useEffect + fetch for initial page data in the App Router.
  • Control caching deliberately: fetch(url, { cache: 'force-cache' | 'no-store' }) or export const revalidate = N. State the choice — don't leave it implicit and then wonder why data is stale.
  • Mutations use Server Actions ('use server') or route handlers, followed by revalidatePath / revalidateTag. A server action is a public HTTP endpoint: authenticate and authorize inside it, every time. Never assume it can only be called from your own UI.

Components and hooks

  • One component per file, named export, colocated with its styles/tests. Keep components under ~150 lines; extract when a component grows a second responsibility.
  • Derive state, don't duplicate it. If a value is computable from props/state, compute it — no useEffect that syncs one piece of state to another.
  • useEffect is for synchronizing with something outside React (subscriptions, DOM, timers). Data fetching, transformations, and event responses do not belong there.
  • Complete dependency arrays. Fix the design rather than silencing the lint rule.
  • Stable key from entity id — never array index for reorderable/filterable lists.
  • Cleanup in effects: abort in-flight fetches (AbortController), clear timers, remove listeners.
  • useMemo/useCallback/memo only after an actual measured problem, or to keep a referential identity that a dependency array needs. Not by default.

Data and state

  • Server state (anything that lives in the backend) → one server-state library: the one the app already uses (TanStack Query, SWR, RTK Query); if it has none, default to RTK Query (createApi, features add endpoints with injectEndpoints, providesTags/invalidatesTags declared once). Never mirror server state into a slice/Context, and never hand-roll it with useEffect+useState or createAsyncThunk + extraReducers loading flags. Writes are that library's mutations.
  • Client state → the app's existing store (default: Redux Toolkit createSlice), synchronous UI state only (wizard step, selection, toggles). Never API responses or hand-written loading/error flags. Never a second store library beside the first. Local state stays local; lift only as far as needed.
  • createAsyncThunk only for multi-step client orchestration: signal and rejectWithValue required, typed serialisable errors.
  • Typing: explicit types for every request, response and DTO; no any, no Record<string, any>; derive RootState/AppDispatch once and use only typed hooks (useAppSelector, useAppDispatch).
  • Global errors: wrap the base query once (401/expiry, retry only transient failures, serialisable errors); error.tsx, not-found.tsx, and an Error Boundary around each independent feature module.
  • Forms: unsubmitted fields and validation errors in local state or React Hook Form + Zod, never Redux.
  • Context is for dependency injection and low-frequency globals (theme, locale, session): split state from dispatch, memoise the value.
  • Per-request isolation: makeStore() factory, held by a Client Component StoreProvider (useRef), never a module-level singleton.
  • Prefetch in a Server Component and seed the per-request store when the client also reads the data; run independent reads in parallel.
  • Pass AbortSignal to every request. Writes: Server Action + revalidatePath/revalidateTag, or an RTK Query mutation + tag invalidation.
  • Selectors: createSelector for derived/filtered Redux data, selectFromResult for query results; never useSelector(s => s).
  • NEXT_PUBLIC_* is public; secrets unprefixed and server-only; nothing secret or personal in Redux state. Detailed patterns: the reference/ files of the frontend-architecture skill.
  • URL is state: filters, tabs, pagination belong in searchParams so the view is shareable and back/forward works.
  • Every async view handles all four states: loading, empty, error, success. Use loading.tsx and error.tsx (client component with reset) at the route level. For the full failure path — boundary placement, global-error.tsx, server-action failures, the status→UX map, server validation onto form fields, retry/offline — load [[error-handling-frontend]], which applies to this baseline too.

Forms

  • react-hook-form + zodResolver, sharing the same Zod schema with server-side validation.
  • Native <form> semantics; labels tied to inputs; disable submit while pending; show field-level errors wired via aria-describedby and aria-invalid.
  • Server-side validation is authoritative. Client validation is a UX affordance only.

Performance

  • next/image for images (never a raw <img> for content images); next/font for fonts.
  • next/dynamic for heavy client-only widgets (modals, data grids, charts, editors, maps), called from a Client Component (a dynamic import in a Server Component does not code-split client code); measure the gain. <Suspense> with a real skeleton, not a spinner-only page.
  • Watch bundle cost: don't import a whole library for one helper (import debounce from 'lodash/debounce', not import { debounce } from 'lodash'); prefer date-fns/Intl over moment.
  • Stream where it helps: <Suspense> around slow sections so the shell paints immediately.

Accessibility

  • Semantic elements first. A <div onClick> is a bug — use <button>.
  • Keyboard reachable, visible focus, logical tab order; focus moves into dialogs and returns on close.
  • Images: meaningful alt, or alt="" when decorative. Icon-only buttons need aria-label.
  • Don't encode meaning in colour alone; text contrast ≥ 4.5:1.

Security

  • NEXT_PUBLIC_* is public. Anything in it ships to the browser. Server-only secrets get an unprefixed name and are read only in server code.
  • Never dangerouslySetInnerHTML with content you did not author. If unavoidable, sanitize with DOMPurify — and prefer rendering as text.
  • Never build a URL for fetch/redirect from raw user input without an allowlist (open redirect, SSRF).
  • Tokens in httpOnly, Secure, SameSite cookies — not localStorage.
  • Authorization decisions belong on the server. Hiding a button is presentation, not access control.
  • Never render backend error details or stack traces to the user.
  • Keep a Content-Security-Policy in next.config / middleware; avoid unsafe-inline scripts.

Testing

  • Vitest/Jest + React Testing Library. Query by role and accessible name — not test-ids or class names.
  • Test what the user does, not implementation details. MSW for network stubbing.
  • Playwright for the handful of critical end-to-end flows (auth, checkout, primary create path).

Individual skills in this repo

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

相關技能