nextjs-mastery
npx skills add https://github.com/umarfarooqoo7/skills --skill nextjs-mastery
Agent 安装分布
Skill 文档
Next.js Mastery (v15/16 + React 19)
Code examples:
- examples-core.md â Components, routing, data fetching, mutations
- examples-platform.md â Caching, errors, auth, i18n, security, proxy
Breaking Changes from v14
| Change | Migration |
|---|---|
| fetch is uncached by default | Opt in: cache: 'force-cache' or next: { revalidate: N } |
| GET Route Handlers uncached | Opt in: export const dynamic = 'force-static' |
| params, searchParams are Promises | await params in Server Components, use(params) in Client Components |
| cookies(), headers() are async | Must await â sync access removed in v16 |
useFormState deprecated |
Use useActionState from react (not react-dom) |
middleware.ts deprecated |
Rename to proxy.ts, export proxy function (runs on Node.js, not Edge) |
next/image priority deprecated |
Use preload prop instead |
Parallel routes require default.tsx |
Builds fail without them â add to every @slot directory |
Migration codemod: npx @next/codemod@canary middleware-to-proxy .
File Conventions
app/
âââ layout.tsx # Shared wrapper (persists across navigations)
âââ template.tsx # Re-mounted on every navigation
âââ page.tsx # Route UI
âââ loading.tsx # Suspense fallback
âââ error.tsx # Error boundary ('use client' required)
âââ not-found.tsx # 404 UI
âââ global-error.tsx # Root layout error boundary (must include <html>/<body>)
âââ route.ts # API endpoint (no page.tsx in same dir)
âââ default.tsx # Parallel route fallback (required per slot)
âââ opengraph-image.tsx # OG image generation
âââ proxy.ts # Network proxy (replaces middleware.ts)
Patterns
1. Server Components (default)
Use for data fetching, secrets, heavy computation. Wrap slow data in <Suspense> to stream. Colocate data fetching â fetch in the component that renders the data. See examples: streaming.
2. Client Components
Add 'use client' only for interactivity (hooks, event handlers, browser APIs). Use useActionState for Server Action state (replaces useFormState). Use use() to unwrap Promises passed from Server Components. See examples: client and examples: use().
3. Server Actions
Mark with 'use server'. Validate all inputs with Zod. Check auth before mutations. Return errors as values â don’t throw for expected failures. Call revalidateTag/revalidatePath after mutations. See examples: actions.
4. Route Handlers
Auth guard on every POST/PUT/DELETE. Zod schema validation on request body. Return proper status codes (201 created, 400 bad request, 401 unauthorized, 404 not found). GET handlers are uncached by default. See examples: route handlers.
5. Parallel Routes
Use @slot directories for independent loading states. Every slot must have default.tsx. Each slot streams independently via its own loading.tsx. See examples: parallel.
6. Intercepting Routes
Use (.) prefix to intercept same-level routes (modals). Provide full-page fallback for direct navigation and refresh. Always include default.tsx in the @modal slot. See examples: intercepting.
7. Metadata & SEO
Use generateMetadata for dynamic per-page metadata. Use generateStaticParams for static generation. Call notFound() when data doesn’t exist. See examples: metadata.
Caching
fetch (v15+ defaults)
fetch is uncached by default. Opt in explicitly:
| Pattern | Option |
|---|---|
| Uncached (default) | fetch(url) |
| Static | fetch(url, { cache: 'force-cache' }) |
| ISR | fetch(url, { next: { revalidate: 60 } }) |
| Tagged | fetch(url, { next: { tags: ['products'] } }) |
“use cache” directive (v16)
Enable with cacheComponents: true in next.config.ts. Replaces unstable_cache.
- Apply at file, component, or function level
- Configure with
cacheLife()andcacheTag()fromnext/cache - Cannot call
cookies()/headers()inside â pass as arguments - Invalidate with
updateTag()(read-your-writes) orrevalidateTag()
| Profile | stale | revalidate | expire |
|---|---|---|---|
seconds |
30s | 1s | 1min |
minutes |
5min | 1min | 1hr |
hours |
5min | 1hr | 1day |
days |
5min | 1day | 1week |
weeks |
5min | 1week | 30days |
max |
5min | 30days | 1year |
See examples: use cache.
Error Handling
- Expected errors â return as values from Server Actions (
{ message: "..." }), not throw error.tsxâ must be'use client'; catches errors in route segment children (not the layout at the same level)global-error.tsxâ catches root layout errors; must include<html>and<body>not-found.tsxâ shown whennotFound()is called- Production â only
digest(hash) is sent to client, not the error message reset()â re-render the segment without a full page reload
See examples: errors.
Auth (Auth.js v5)
- Single
auth()function replacesgetServerSession,getSession,useSession - JWT strategy â no DB adapter needed
AUTH_prefixed env vars auto-inferred by providers- Protect routes in
proxy.tsviaauthorizedcallback - Always verify auth in Server Actions individually â don’t rely solely on proxy
See examples: auth.
Security
- Set CSP, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy via
headers()innext.config.ts - Nonce-based CSP in
proxy.tsfor strict mode (disables static rendering) NEXT_PUBLIC_values are frozen at build time â use API routes for runtime-configurable public values- All
.env*.localfiles in.gitignore
See examples: security.
Internationalization
app/[lang]/segment +proxy.tsfor locale detection/redirect- Dictionary pattern with
server-only(zero client bundle) generateStaticParamsfor static rendering per locale- Libraries: next-intl, next-international, paraglide-next
See examples: i18n.
Tooling (v16)
| Tool | Status | Config |
|---|---|---|
| Turbopack | Default bundler | Opt out: --webpack |
| React Compiler | Stable, opt-in | reactCompiler: true in next.config.ts |
| proxy.ts | Replaces middleware.ts | Node.js runtime (not Edge) |
React Compiler auto-memoizes components and hooks â eliminates manual useMemo, useCallback, React.memo.
Testing
| Layer | Tool | Use for |
|---|---|---|
| Unit/Integration | Vitest + React Testing Library | Client Components, sync Server Components, utilities |
| E2E | Playwright | Async Server Components, full-stack flows, hydration |
Playwright for async Server Components because it makes real HTTP requests â unit test runners can’t simulate the server-to-client pipeline.
Rules
Do
- Server Components by default â
'use client'only for interactivity - Colocate data fetching â fetch in the component that uses it
- Wrap slow data in Suspense â stream, don’t block
- Validate all inputs â Zod in Server Actions and route handlers
- Check auth in every mutation â session guard in actions and route handlers
- Use
notFound()â when a DB lookup returns null - Provide
default.tsxâ for every parallel route slot - Await all dynamic APIs â params, searchParams, cookies(), headers()
- Return errors as values â from Server Actions, don’t throw for expected failures
- Set security headers â CSP, X-Frame-Options, HSTS in production
Don’t
- Don’t assume fetch is cached â uncached since v15; opt in explicitly
- Don’t pass non-serializable data across Server/Client boundary â no functions, classes, Dates
- Don’t use hooks in Server Components â no useState, useEffect, useRef
- Don’t fetch in Client Components â lift to Server Component parent or use a query library
- Don’t skip error boundaries â
error.tsx('use client') per route segment - Don’t pass raw input to the database â always validate with Zod
- Don’t use
useFormStateâ deprecated; useuseActionStatefromreact - Don’t use
middleware.tsâ deprecated; rename toproxy.ts - Don’t call cookies()/headers() inside
'use cache'â read outside, pass as arguments