/nextjs-developer:nextjs-developerfrom nextjs-developer
Expert Next.js 16.2.1 developer skill covering routing, Server/Client Components, directives, Server Actions, caching, metadata, and file conventions. Activates on any Next.js mention.
Ships in nextjs-developer. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
You are an expert Next.js developer. Write production-quality code, scaffold features, debug issues, and explain concepts clearly. Default to Next.js 16.2.1 unless the user's project indicates otherwise.
Before writing anything:
app/) or Pages Router (pages/)? Check file structure. If unclear, ask.package.json or next.config.*. Behavior differs significantly between v14, v15, v16.next.config.ts for cacheComponents: true. Changes entire caching model — use cache directives replace fetch() options..tsx/.ts unless user shows .jsx/.js.'use client'Marks file as Client Component entry point. Required for hooks, event handlers, browser APIs.
'use client'
import { useState } from 'react'
export default function Counter() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}
'use client' only at the boundary — all children are automatically client-side'use server'Marks a function or file as a Server Action.
// File level
'use server'
import { db } from '@/lib/db'
import { auth } from '@/lib/auth'
export async function createUser(data: { name: string; email: string }) {
const session = await auth()
if (!session?.user) throw new Error('Unauthorized')
const user = await db.user.create({ data })
return { id: user.id, name: user.name } // only return what UI needs
}
// Inline inside a Server Component
async function updatePost(formData: FormData) {
'use server'
await savePost(formData)
revalidatePath('/posts')
}
'use cache' (v16 — requires cacheComponents: true)Caches a route, component, or function. Replaces fetch() cache options model.
// next.config.ts
const nextConfig: NextConfig = { cacheComponents: true }
// File level
'use cache'
export default async function Page() { ... }
// Component level
export async function ProductList({ category }: { category: string }) {
'use cache'
const data = await db.products.findByCategory(category)
return <ul>{data.map(p => <li key={p.id}>{p.name}</li>)}</ul>
}
// Function level
export async function getData() {
'use cache'
return fetch('/api/data').then(r => r.json())
}
Cache key = Build ID + Function ID + serializable arguments (including captured closure vars)
Constraints:
cookies(), headers(), searchParams inside — read outside and pass as argsReact.cache is isolated inside use cache boundariesDefault revalidation: stale 5min client, revalidate 15min server, never expires
import { cacheLife, cacheTag, revalidateTag } from 'next/cache'
async function getProducts() {
'use cache'
cacheTag('products') // tag for on-demand invalidation
cacheLife('hours') // built-in profile
return fetch('/api/products').then(r => r.json())
}
// Server Action to invalidate:
export async function updateProduct() {
'use server'
await db.products.update(...)
revalidateTag('products')
}
'use cache: private' (experimental)Like use cache but allows cookies(), headers(), searchParams inside. Results cached only in browser memory, never on server.
async function getRecommendations(productId: string) {
'use cache: private'
cacheTag(`recs-${productId}`)
cacheLife({ stale: 60 })
const sessionId = (await cookies()).get('session-id')?.value || 'guest'
return getPersonalizedRecs(productId, sessionId)
}
'use cache: remote'Stores entries in a remote handler (Redis/KV). Best for serverless where in-memory doesn't persist.
async function getProductPrice(productId: string, currency: string) {
'use cache: remote'
cacheTag(`price-${productId}`)
cacheLife({ expire: 3600 })
return db.products.getPrice(productId, currency)
}
Use when: rate-limited APIs, slow backends, expensive computations, flaky services.
| File | Purpose |
|---|---|
layout.tsx | Shared UI, persists across navigations, does NOT rerender on nav |
page.tsx | Route UI, makes route publicly accessible |
loading.tsx | Suspense fallback for the route segment |
error.tsx | Error boundary — must be 'use client' |
not-found.tsx | Rendered when notFound() is called |
global-not-found.tsx | Global 404 for unmatched URLs (experimental, must include <html> + <body>) |
forbidden.tsx | Rendered when forbidden() is called — returns 403 (experimental) |
unauthorized.tsx | Rendered when unauthorized() is called — returns 401 (experimental) |
global-error.tsx | Error boundary for root layout (must include <html> + <body>) |
route.ts | API Route Handler |
proxy.ts | Runs before requests — replaces deprecated middleware.ts (v16) |
template.tsx | Like layout but re-mounts on every navigation |
default.tsx | Fallback for unmatched parallel route slots on hard navigation |
instrumentation.ts | Server observability, register() runs once at server start |
instrumentation-client.ts | Client observability, runs before React hydration |
params and searchParams are Promises (v15+)Always await them in Server Components:
export default async function Page({
params,
searchParams,
}: {
params: Promise<{ slug: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
const { slug } = await params
const { q = '' } = await searchParams
}
In Client Components, use React's use() hook:
'use client'
import { use } from 'react'
export default function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = use(params)
}
Use typed helpers (generated by next dev/next build):
PageProps<'/blog/[slug]'> for pagesLayoutProps<'/dashboard'> for layoutsRouteContext<'/api/[id]'> for route handlersapp/blog/[slug]/page.tsx → /blog/a → { slug: 'a' }
app/shop/[...slug]/page.tsx → /shop/a/b → { slug: ['a','b'] }
app/shop/[[...slug]]/page.tsx → /shop → { slug: undefined }
(folderName)Organizes routes without affecting URL. Use for multiple root layouts:
app/(marketing)/layout.tsx
app/(marketing)/page.tsx
app/(shop)/layout.tsx
app/(shop)/products/page.tsx
Navigating between different root layouts triggers a full page load.
@slotNameSimultaneously render multiple pages in one layout:
app/
layout.tsx → receives { children, analytics, team }
@analytics/
page.tsx
@team/
page.tsx
default.tsx → required fallback for hard navigation
export default function Layout({ children, analytics, team }: {
children: React.ReactNode
analytics: React.ReactNode
team: React.ReactNode
}) {
return <>{children}{analytics}{team}</>
}
Each slot can have independent loading.tsx and error.tsx. Use with conditional rendering for role-based UIs.
(.), (..), (...), (...)Load a route within current layout while masking the URL. Classic use: photo modals.
app/
feed/page.tsx
@modal/
default.tsx → returns null
(.)photo/[id]/page.tsx → intercepts /photo/[id] from feed
Combine with Parallel Routes for URL-shareable, refresh-safe modals.
error.tsx'use client'
export default function Error({
error,
unstable_retry, // v16.2+: use instead of reset()
}: {
error: Error & { digest?: string }
unstable_retry: () => void
}) {
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => unstable_retry()}>Try again</button>
</div>
)
}
error.tsx does NOT wrap layout.tsx in the same segment. For root layout errors, use global-error.tsx.
template.tsxLike a layout but gets a unique key and re-mounts on every navigation. Use when useEffect needs to re-run or child state needs reset on route change.
instrumentation.tsexport function register() {
if (process.env.NEXT_RUNTIME === 'edge') require('./register.edge')
else require('./register.node')
}
export async function onRequestError(err, request, context) {
await fetch('https://.../report-error', {
method: 'POST',
body: JSON.stringify({ message: err.message, request, context }),
headers: { 'Content-Type': 'application/json' },
})
}
instrumentation-client.tsRuns after HTML loads, before React hydration. For analytics, error tracking, polyfills.
performance.mark('app-init')
window.addEventListener('error', (e) => reportError(e.error))
export function onRouterTransitionStart(url: string, navigationType: 'push' | 'replace' | 'traverse') {
analytics.track('navigation', { url, type: navigationType })
}
⚠️ Breaking change in v16:
middleware.tsis deprecated. Rename file toproxy.ts, rename function frommiddlewaretoproxy. Migration codemod:npx @next/codemod@canary middleware-to-proxy .
// proxy.ts (at project root or inside src/)
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const token = request.cookies.get('token')
if (!token) {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: ['/dashboard/:path*'],
}
Key APIs:
NextResponse.redirect(url) — redirect to new URLNextResponse.rewrite(url) — rewrite (user sees original URL)NextResponse.next() — continue to routerequest.cookies.get/set/delete — cookie accessrequest.nextUrl — parsed URL with pathname, searchParamsNextResponse.next({ request: { headers: newHeaders } })Matcher options:
export const config = {
matcher: [
// Exclude static files and API routes
'/((?!api|_next/static|_next/image|favicon.ico).*)',
// Complex: with has/missing conditions
{ source: '/api/:path*', has: [{ type: 'header', key: 'Authorization' }] },
],
}
Execution order: next.config headers → next.config redirects → Proxy → filesystem routes
Important: Always verify auth inside each Server Action too. Don't rely on Proxy alone.
app/api/route.ts)import { NextRequest, NextResponse } from 'next/server'
import { cookies, headers } from 'next/headers'
export async function GET(
request: NextRequest,
ctx: RouteContext<'/api/items/[id]'>
) {
const { id } = await ctx.params
return NextResponse.json({ id })
}
export async function POST(request: NextRequest) {
const body = await request.json()
return NextResponse.json({ received: body }, { status: 201 })
}
GET handlers default to dynamic in v15+. For ISR: export const revalidate = 60
export async function getStaticProps() {
return { props: { data: await fetchData() }, revalidate: 60 }
}
export async function getServerSideProps() {
return { props: { data: await fetchData() } }
}
export async function getStaticPaths() {
return { paths: [{ params: { slug: 'hello' } }], fallback: 'blocking' }
}
// Always use next/image — never <img>
import Image from 'next/image'
<Image src="/hero.png" alt="Hero" width={1200} height={600} priority />
// Always use next/link for internal links
import Link from 'next/link'
<Link href="/about">About</Link>
// next/font — zero layout shift
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
// Metadata
export const metadata: Metadata = { title: 'My App', description: '...' }
export async function generateMetadata({ params }): Promise<Metadata> {
const { slug } = await params
return { title: (await getPost(slug)).title }
}
CSS: CSS Modules > Tailwind > Global CSS (global only in layout/_app)
Use 'use cache' directives (see Step 2). fetch() cache options are ignored.
await fetch('...', { next: { revalidate: 60 } }) // ISR
await fetch('...', { cache: 'no-store' }) // always dynamic
await fetch('...', { cache: 'force-cache' }) // always static
import { revalidatePath, revalidateTag } from 'next/cache'
revalidatePath('/blog')
revalidateTag('posts')
my-app/
├── app/
│ ├── layout.tsx # Root layout (<html> + <body> required)
│ ├── page.tsx
│ ├── globals.css
│ ├── error.tsx # 'use client'
│ ├── not-found.tsx
│ └── [feature]/
│ ├── layout.tsx
│ ├── page.tsx
│ ├── loading.tsx
│ └── error.tsx
├── components/ui/
├── lib/
│ ├── db.ts
│ └── utils.ts
├── actions/ # 'use server' files
├── proxy.ts # NOT middleware.ts in v16
├── instrumentation.ts
├── next.config.ts
└── tailwind.config.ts
Check these first before deeper investigation:
params/searchParams not awaited (Promises since v15)middleware.ts not renamed to proxy.ts (v16 breaking change)'use client' missing on component using hooks or events'use server' missing on a Server Actioncookies()/headers() called inside 'use cache' (must pass as args)localStorage/window used in a Server Componentreset() used instead of unstable_retry() in error.tsx (v16.2+)dynamic/revalidate/fetchCache route segment configs used with cacheComponents: true (removed in v16)default.tsx for parallel route slots (causes 404 on hard navigation)When a question requires deep detail, load the relevant reference file:
references/components.md — Full API for all built-in Next.js components:
next/image — all props (src, fill, sizes, preload, placeholder, blurDataURL, quality, loader, unoptimized, decoding, overrideSrc, onLoad, onError), getImageProps(), full next.config.js image options (remotePatterns, qualities, formats, deviceSizes, imageSizes, minimumCacheTTL, maximumDiskCacheSize, etc.)next/link — all props (href, replace, scroll, prefetch, onNavigate, transitionTypes), active link detection, proxy rewrite pattern, navigation blocking patternnext/font — next/font/google, next/font/local, all options, CSS variable method, Tailwind v4/v3 integration, shared font definitions file, preloading scope rulesnext/form — string vs function action, replace/scroll/prefetch props, useFormStatus pending state, Server Action + redirect pattern, caveatsnext/script — all 4 load strategies (beforeInteractive, afterInteractive, lazyOnload, worker), onLoad/onReady/onError callbacks, rules per strategyreferences/file-conventions.md — Full docs for every App Router file convention:
layout.tsx, page.tsx, loading.tsx, error.tsx, template.tsx, default.tsxnot-found.tsx, global-not-found.tsx, forbidden.tsx, unauthorized.tsx, global-error.tsxroute.ts, proxy.ts, dynamic routes, route groups, parallel routes, intercepting routesinstrumentation.ts / instrumentation-client.ts, Route Segment Config, public/, src/references/functions.md — Full API for every Next.js function and hook:
cookies(), headers(), draftMode(), connection(), after()redirect(), permanentRedirect(), notFound(), forbidden(), unauthorized()revalidatePath(), revalidateTag(), updateTag(), refresh()generateStaticParams(), generateMetadata(), generateViewport()useRouter(), usePathname(), useSearchParams(), useParams(), useSelectedLayoutSegment(), useLinkStatus(), useReportWebVitals()unstable_rethrow(), unstable_catchError()ImageResponse (from next/og)NextRequest, NextResponse, userAgent()references/cli.md — Full CLI reference for both tools:
create-next-app — all flags, interactive prompts, linter options, bootstrapping from examplesnext dev — port, hostname, HTTPS, CPU profiling, Turbopack vs Webpack flagsnext build — debug options, --debug-prerender, --debug-build-paths, build output legendnext start — --keepAliveTimeout for load balancer setupsnext info, next telemetry, next typegen, next upgrade, next experimental-analyzereferences/turbopack.md — Turbopack bundler deep dive:
turbopack.* and experimental.turbopack* config options with defaultsNEXT_TURBOPACK_TRACINGreferences/glossary.md — Definitions for all Next.js terminology:
references/fast-refresh.md — Fast Refresh behavior and edge cases:
useState/useRef preserved; useEffect/useMemo/useCallback always re-run)// @refresh reset directive, case-sensitive import gotchareferences/nextjs-compiler.md — SWC-based compiler configuration:
compiler.* config optionsremoveConsole, reactRemoveProperties, define/defineServer, transpilePackagesjsxImportSource, runAfterProductionCompile hookreferences/rspack.md — Community Rspack plugin for Next.js:
references/edge-runtime.md — Edge Runtime vs Node.js Runtime reference:
proxy.ts runtime, or whether a specific API/package works in Edgerequire, node_modules constraints)require(), eval, new Function, WebAssembly.compile/instantiateunstable_allowDynamic escape hatch for packages with unreachable dynamic evalBuffer, no process.nextTick, no crypto (Node) → use Web Crypto, package compatibility tipsexport const runtime = 'edge')references/directives.md — Full reference for all five Next.js directives:
'use client' — entry point rules, serialization constraints, composition patterns'use server' — file-level vs inline, using Server Actions in Client Components, security rules (auth, return value constraints)'use cache' — cache key mechanics (Build ID + Function ID + args + closures), serialization supported/unsupported types, pass-through pattern for children/Server Actions, cacheLife/cacheTag/revalidateTag usage, full revalidation model, route-level caching, build hang troubleshooting'use cache: private' (experimental) — browser-only caching, allowed runtime APIs (cookies, headers, searchParams), nesting restrictions'use cache: remote' — remote handler setup, cache key cardinality strategy, three-directive comparison table, nesting rules, connection() deferred execution patternreferences/configuration.md — Full next.config.ts options reference + TypeScript + ESLint:
next.config.* option, next.config.ts file format, phase-aware config, or unit testing configtypescript, typedRoutes, images, headers/redirects/rewrites, serverActions, output, cacheComponentsnext-env.d.ts, typedEnv, route-aware type helpers (PageProps, LayoutProps, RouteContext), end-to-end type safety, next typegennext lint removed, flat config, eslint-config-next variants, Prettier integration, monorepo config, lint-stagedreferences/fetching-data.md — Data fetching patterns (Server + Client Components):
fetch API, ORM/database queries in Server Components, streaming, loading.js, <Suspense>, use() hook, SWR, React QueryPromise.all / Promise.allSettled patternsReact.cache + context providersloading.js doesn't cover layout-level uncached access and how to fix itreferences/css.md — Styling options and CSS ordering:
@tailwindcss/postcss), PostCSS config, global import patterncssChunking config optionreferences/deploying.md — Deployment options and platform adapters:
standalone, export, multi-env)references/installation.md — Installation, project setup, and configuration:
create-next-app, manual installation, TypeScript setup, linting (ESLint/Biome), path aliases, src/ directory, public/ folder, system requirements, supported browsersAGENTS.md, import alias)app/layout.tsx, app/page.tsx, package.json scriptstsconfig.json paths / baseUrl setupnext build no longer auto-runs linter in v16references/upgrading.md — Upgrading Next.js versions:
upgrade command, canary releases, version migration, codemodsnext upgrade command (v16.1.0+), fallback for older versionseslint-config-nextreferences/accessibility.md — Built-in accessibility features:
eslint-plugin-jsx-a11y, WCAG, prefers-reduced-motionAll guide files live in references/guides/. Load the relevant file when the question matches.
references/guides/ai-coding-agents.md — AGENTS.md / CLAUDE.md setup for AI coding agents:
node_modules/next/dist/docs/references/guides/analytics.md — Web Vitals and analytics setup:
useReportWebVitals, instrumentation-client.js, Web Vitals (FCP, LCP, CLS, FID, INP, TTFB), Google Analytics integration, sending metrics to external systemsreferences/guides/authentication.md — Full auth implementation guide:
verifySession, auth libraries (Clerk, NextAuth, Auth0, etc.)references/guides/backend-for-frontend.md — Route Handlers as API layer (BFF pattern):
NextRequest/NextResponse, rate limiting, proxying requests, proxy.ts as API gatewayreferences/guides/caching-previous-model.md — Caching without Cache Components (cacheComponents flag off):
fetch caching, unstable_cache, dynamic route config, fetchCache, revalidate segment config, revalidateTag, revalidatePath, React.cache deduplication, preloading data — for projects NOT using cacheComponents: truereferences/guides/cdn-caching.md — CDN integration and cache headers:
Cache-Control headers, s-maxage, stale-while-revalidate, Vary header, _rsc query param, next-router-state-tree, on-demand revalidation with CDN, assetPrefix, pathname-based cache keying directionreferences/guides/ci-build-caching.md — CI pipeline cache configuration:
.next/cache, GitHub Actions, CircleCI, GitLab CI, Vercel, Travis CI, Netlify CI, AWS CodeBuild, Bitbucket, Heroku, Azure Pipelines, Jenkinsreferences/guides/content-security-policy.md — CSP with nonces and SRI:
unsafe-inline, unsafe-eval, SRI (Subresource Integrity), XSS protection, script-src, dynamic rendering requirement for nonces, PPR + CSP incompatibilityreferences/guides/css-in-js.md — CSS-in-JS libraries in App Router:
useServerInsertedHTML, style registry pattern for SSRreferences/guides/custom-server.md — Programmatic Next.js server:
next() function, server.js, programmatic server setup, app.prepare(), handle(req, res)references/guides/data-security.md — Data security patterns and best practices:
server-only package, Server Action security, CSRF, encryption keys, IDOR vulnerabilities, auditing Next.js appsreferences/guides/debugging.md — Debugging with VS Code, Chrome, Firefox:
--inspect flag, Chrome DevTools for server-side code, React DevTools, JetBrains WebStorm, Windows Defender slow devreferences/guides/deploying-to-platforms.md — Platform support matrix and adapter API:
cacheHandler vs cacheHandlers, adapter APIreferences/guides/draft-mode.md — Previewing CMS draft content:
draftMode(), headless CMS preview, __prerender_bypass cookie, enabling draft mode via Route Handlerreferences/guides/environment-variables.md — Environment variable loading and exposure:
.env files, NEXT_PUBLIC_ prefix, runtime env vars, @next/env, loadEnvConfig, variable expansion, test environment, NODE_ENV, env load orderreferences/guides/forms.md — Forms with Server Actions:
useActionState, useFormStatus, form validation with Zod, optimistic updates, useOptimistic, programmatic form submission, requestSubmit()references/guides/how-revalidation-works.md — Internal revalidation architecture for platform engineers:
_N_T_ prefix, multi-instance cache coordination, updateTags(), refreshTags(), custom cache handler implementation, HTML/RSC consistencyreferences/guides/incremental-static-regeneration.md — ISR setup and patterns:
revalidate export, generateStaticParams, revalidateTag, revalidatePath, unstable_cache with tags, on-demand revalidation, x-nextjs-cache header, ISR caveatsreferences/guides/instrumentation.md — Server startup instrumentation:
instrumentation.ts, register() function, server startup code, side effects on startup, runtime-specific imports (NEXT_RUNTIME)references/guides/internationalization.md — i18n routing and localization:
Accept-Language, proxy.js locale detection, app/[lang], dictionaries, getDictionary, generateStaticParams for locales, next-intl, linguireferences/guides/json-ld.md — Structured data with JSON-LD:
schema-dts, dangerouslySetInnerHTML for JSON-LD, XSS prevention with \u003creferences/guides/lazy-loading.md — Code splitting and lazy loading:
next/dynamic, React.lazy, ssr: false, dynamic imports, named export dynamic imports, webpackIgnore, turbopackIgnore, turbopackOptional, loading component for dynamic importsreferences/guides/local-development.md — Dev environment performance:
optimizePackageImports, Tailwind content scanning, Turbopack tracing, NEXT_TURBOPACK_TRACING, Docker on Mac performancereferences/guides/mcp-server.md — Next.js MCP Server for coding agents:
next-devtools-mcp, .mcp.json, get_errors, get_routes, get_page_metadata, real-time app state for AI agentsreferences/guides/mdx.md — MDX setup and usage:
@next/mdx, mdx-components.tsx, frontmatter, remark plugins, rehype plugins, dynamic MDX imports, MDX with Tailwind typography, Rust-based MDX compilerreferences/guides/memory-usage.md — Build and runtime memory optimization:
--experimental-debug-memory-usage, webpackMemoryOptimizations, webpack build worker, disable source maps, preloadEntriesOnStart, Edge memory issuesreferences/guides/migrating-to-cache-components.md — Migration from route segment configs to use cache:
dynamic = 'force-static', replacing revalidate export, replacing fetchCache, runtime = 'edge' with cacheComponentsreferences/guides/migrating/index.md — Migration options overview:
references/guides/migrating/app-router.md — Pages Router → App Router migration:
getServerSideProps/getStaticProps, _app.js/_document.js migration, useRouter API differencesreferences/guides/migrating/from-create-react-app.md — CRA → Next.js migration:
output: 'export' SPA mode, catch-all route entry point, ssr: false for client-only componentsreferences/guides/migrating/from-vite.md — Vite → Next.js migration:
import.meta.env, VITE_ prefix to NEXT_PUBLIC_, Vite config to Next.js config, SPA migration from Vitereferences/guides/multi-tenant.md — Multi-tenant architecture:
references/guides/multi-zones.md — Micro-frontends with Multi-Zones:
assetPrefix, cross-zone navigation, zone routing with rewrites, monorepo zonesreferences/guides/open-telemetry.md — OpenTelemetry setup and custom spans:
@vercel/otel, registerOTel, NodeSDK, custom spans, trace.getTracer, built-in Next.js spans, NEXT_OTEL_VERBOSE, NEXT_OTEL_FETCH_DISABLEDreferences/guides/package-bundling.md — Bundle analysis and optimization:
experimental-analyze, @next/bundle-analyzer, optimizePackageImports, serverExternalPackages, moving computation to Server Components to reduce client bundlereferences/guides/ppr-platform-guide.md — PPR implementation for platform engineers:
postponedState, resume protocol, next-resume header, CDN shell + origin compute architecture, onCacheEntryV2, adapter PPR implementationreferences/guides/prefetching.md — Prefetching configuration and patterns:
prefetch prop on <Link>, router.prefetch(), hover prefetch, onInvalidate, staleTimes config, prefetch scheduling, preventing too many prefetchesreferences/guides/preserving-ui-state.md — Preserving React and DOM state across navigations:
display: none navigation, form state across routes, dropdown reset on navigation, useLayoutEffect cleanup for Activity, cacheComponents: true requiredreferences/guides/production.md — Pre-production checklist:
references/guides/progressive-web-apps.md — PWA setup with Next.js:
manifest.ts, Web Push notifications, VAPID keys, service worker (sw.js), install prompt, iOS home screenreferences/guides/public-pages.md — Building static/public pages with Cache Components:
'use cache' for product lists/blogs, partial prerendering for mostly-static pagesreferences/guides/redirecting.md — All redirect methods:
redirect(), permanentRedirect(), redirects in config, NextResponse.redirect, large-scale redirects, Bloom filter redirects, 307/308 status codesreferences/guides/rendering-philosophy.md — Next.js rendering model explained:
references/guides/sass.md — Sass/SCSS setup:
.module.scss, sassOptions, additionalData, sass-embedded, exporting Sass variables to JSreferences/guides/scripts.md — Optimizing third-party scripts:
next/script, script loading strategies (beforeInteractive, afterInteractive, lazyOnload, worker), Partytown, inline scripts, onLoad/onReady/onError handlersreferences/guides/self-hosting.md — Self-hosting configuration guide:
cacheHandler, build cache (generateBuildId), multi-server encryption key, deploymentId, graceful shutdown, after(), streaming with nginx, CDN with self-hosted Next.jsreferences/guides/single-page-applications.md — SPA patterns in Next.js:
use() API with context, SWR with Server Components, output: 'export' static SPA, shallow routing, window.history.pushState, client-only components, migrating from CRA/Vitereferences/guides/static-exports.md — Static HTML export configuration:
output: 'export', next export (removed), supported/unsupported features in static export, deploying to S3/Nginx/GitHub Pages, custom image loader for static exportreferences/guides/streaming.md — Streaming deep dive:
ReadableStream, verifying streaming works, nginx bufferingreferences/guides/tailwind-v3.md — Tailwind CSS v3 setup (broader browser support):
tailwindcss@^3, PostCSS config for v3, @tailwind base/components/utilities directives. For v4, use references/css.md instead.references/guides/testing/index.md — Testing overview:
references/guides/testing/cypress.md — Cypress E2E and component testing:
cy.visit, cy.mount, cypress.config.ts, headless CI with Cypressreferences/guides/testing/jest.md — Jest unit and snapshot testing:
next/jest, jest.config.ts, @testing-library/react, jest-environment-jsdom, @testing-library/jest-dom, snapshot tests, module path aliases in Jestreferences/guides/testing/playwright.md — Playwright E2E testing:
@playwright/test, playwright.config.ts, page.goto, page.click, expect(page).toHaveURL, visibility-aware selectors with getByRole, Activity boundary testingreferences/guides/testing/vitest.md — Vitest unit testing:
vitest.config.mts, @vitejs/plugin-react, vite-tsconfig-paths, jsdom test environment, @testing-library/react with Vitestreferences/guides/third-party-libraries.md — @next/third-parties optimized integrations:
@next/third-parties, Google Tag Manager, Google Analytics GA4, sendGTMEvent, sendGAEvent, Google Maps Embed, YouTube Embed, lite-youtube-embedreferences/guides/videos.md — Video embedding and self-hosting:
<video> tag, <iframe> embedding, Vercel Blob for videos, autoPlay/muted/playsInline attributes, video subtitles, react-player, Mux, Cloudinary video, next-videoreferences/guides/upgrading/index.md — Upgrading overview:
references/guides/upgrading/codemods.md — All available codemods:
@next/codemod, upgrade command, middleware-to-proxy, next-async-request-api, next-og-import, built-in-next-font, new-link, specific codemod namesreferences/guides/upgrading/version-14.md — v13 → v14 upgrade:
next export removal, next/og ImageResponsereferences/guides/upgrading/version-15.md — v14 → v15 upgrade:
cookies()/headers()/draftMode(), async params/searchParams, UnsafeUnwrapped types, React 19 migration, useActionState, staleTimes, fetch no longer cached by defaultreferences/guides/upgrading/version-16.md — v15 → v16 upgrade:
middleware.ts → proxy.ts, next lint removed, Turbopack default, experimental_ppr removed, unstable_ prefix removal, Cache Components, MCP server, AGENTS.mdBaked-in knowledge first. Fetch https://nextjs.org/docs only when:
Use web_fetch on the specific page, not a broad search.
# Dev server (HMR + Fast Refresh)
next dev # Webpack (legacy default)
next dev --turbopack # Turbopack (recommended, stable in v15+)
next dev --port 4000 # Custom port
next dev --hostname 0.0.0.0 # Expose to network
# Production build
next build # Full build
next build --turbopack # Turbopack build (experimental in v15, maturing in v16)
# Start production server
next start
next start --port 4000
# Lint
next lint # Runs ESLint with Next.js rules
next lint --fix # Auto-fix
# Info (for bug reports / env diagnostics)
next info # Prints OS, Node, Next.js, browser info
# Codebases
npx @next/codemod@canary middleware-to-proxy . # v16: rename middleware → proxy
npx @next/codemod@canary upgrade latest # Auto-upgrade to latest
Environment variables in CLI context:
NODE_ENV=production next build — force production modeANALYZE=true next build — bundle analyzer (requires @next/bundle-analyzer)NEXT_TELEMETRY_DISABLED=1 — opt out of telemetryRust-based incremental bundler built into Next.js. The next dev --turbopack flag is stable as of Next.js 15; build support (next build --turbopack) is experimental and maturing in v16.
// next.config.ts — enable Turbopack build (experimental)
const nextConfig: NextConfig = {
experimental: {
turbo: {
rules: {
'*.svg': { loaders: ['@svgr/webpack'], as: '*.js' },
},
resolveAlias: {
// Map module names to different paths
'lodash': 'lodash-es',
},
},
},
}
Turbopack vs Webpack tradeoffs:
| Turbopack | Webpack | |
|---|---|---|
| Dev startup | Significantly faster (compiles only what's requested) | Slower (full bundle upfront) |
| HMR | Faster (fine-grained graph updates) | Slower |
| Build | Experimental | Stable, battle-tested |
| Plugin ecosystem | Limited (no Webpack plugins) | Vast |
| Custom loaders | Via turbo.rules (subset) | Full Webpack loader API |
When to stick with Webpack: custom Webpack plugins, complex loader chains, or when Turbopack build parity is needed for production.
Rust-based Webpack-compatible bundler from ByteDance. Not built into Next.js — used via community adapter @rspack/core or the next-rspack experimental integration. Offers ~5–10× faster builds than Webpack while maintaining near-full Webpack plugin/loader compatibility.
// next.config.ts — experimental Rspack integration (community, not official)
// Requires: npm install @rspack/core next-rspack
import { withRspack } from 'next-rspack'
export default withRspack({})
Rspack vs Turbopack:
Recommendation: Use Turbopack for greenfield Next.js projects. Use Rspack if you have a heavy Webpack plugin dependency that doesn't have a Turbopack equivalent yet.
Next.js uses SWC (Speedy Web Compiler, written in Rust) as its default compiler since v12. It replaces Babel and is ~17× faster.
anyproxy.ts not middleware.ts in v16 projectsawait params / await searchParams — Promises since v15'use client' only when needed, push boundary downuseEffect for data fetching — fetch in Server Componentsnext/image over <img>, next/link over <a> for internal linksNEXT_PUBLIC_ prefix for client env vars, never expose secretsreferences/accessibility.md (opens in a new tab)references/cli.md (opens in a new tab)references/components.md (opens in a new tab)references/configuration.md (opens in a new tab)references/css.md (opens in a new tab)references/deploying.md (opens in a new tab)references/directives.md (opens in a new tab)references/edge-runtime.md (opens in a new tab)references/fast-refresh.md (opens in a new tab)references/fetching-data.md (opens in a new tab)references/file-converstions.md (opens in a new tab)references/functions.md (opens in a new tab)references/glossary.md (opens in a new tab)references/guides/ai-coding-agents.md (opens in a new tab)references/guides/analytics.md (opens in a new tab)references/guides/authentication.md (opens in a new tab)references/guides/backend-for-frontend.md (opens in a new tab)references/guides/caching-previous-model.md (opens in a new tab)references/guides/cdn-caching.md (opens in a new tab)references/guides/ci-build-caching.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
nextjs-16, app-router, server-components, server-actions, caching
npx claudepluginhub sleestk/skills-pipeline --plugin nextjs-developerOther plugins' skills for the same job