nextjs-app-router-patterns
Skill1 starsChanged 58 days agoMITView on GitHub
Next.js App Router architecture covering Server and Client Components, caching, streaming, Server Actions, route handlers, metadata, images, and Turbopack dev tuning. Use when you say "build a Next.js page", "server or client component", "revalidate this fetch", "add a server action", "parallel routes for a dashboard", or "next dev is slow". Not for framework-agnostic React state, hooks, and animation, use `react-patterns`.
- Reads credentials
- Sends data out
12 other projects use a version of this.
Adopted by
Most recently taken up by
- enes9103/my-claude-agents-skillstheir own version, first seen Sep 28, 2026
- socialadsmentor/sam-agentic-harnesstheir own version, first seen Sep 3, 2026
- Yass5002/agent-skillstheir own version, first seen Aug 27, 2026
- theDRElabs/opencode-configtheir own version, first seen Aug 26, 2026
- idexal/idexal-skillstheir own version, first seen Aug 26, 2026
- amanuelmamo7/Skillstheir own version, first seen Aug 11, 2026
Used with
Projects with it also use tdd.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
AWSSkilltdd
Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
Also in 3 projects that use this
Other versions12 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 12
- Fandry96/k3-agentic-skills★ 27same name
- idexal/idexal-skills★ 13same name
- xfstudio/skills★ 9same name
- GPTtang/skill-atlas★ 4same name
- socialadsmentor/sam-agentic-harness★ 4same name
- ai4brands-design/claude-skills★ 2same name
- CodeWithBehnam/cc-docs★ 2same name
- amanuelmamo7/Skills★ 1same name
- theDRElabs/opencode-config★ 1same name
- zinan92/skills-repo★ 1same name
2 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository59 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .claude/CLAUDE.mdCLAUDE.md
- agentic-engineeringSkill
- ai-regression-testingSkill
- angularSkill
- ansibleSkill
- api-designSkill
- architecture-decision-recordsSkill
- ascend-memorySkill
- ascend-web-hunterSkill
- audio-scribeSkill
- automation-inventorySkill
- backend-patternsSkill
- bashSkill
- build-dependency-managementSkill
- code-formatterSkill
- code-reviewerSkill
- coding-standardsSkill
- dart-flutter-patternsSkill
- database-migrationsSkill
- deployment-patternsSkill
- design-systemSkill
- docker-patternsSkill
- e2e-runbooksSkill
- e2e-testingSkill
- embedded-c-arduinoSkill
- frontend-designSkill
- g-code-3d-printingSkill
- github-opsSkill
- git-workflowSkill
- golang-patternsSkill
- hexagonal-architectureSkill
- home-assistantSkill
- java-coding-standardsSkill
- jetbrains-ide-opsSkill
- jira-integrationSkill
- keycloak-patternsSkill
- kicadSkill
- markdown-writerSkill
- mongodb-patternsSkill
- node-backend-patternsSkill
- observability-and-loggingSkill
- obsidianSkill
- performance-optimizationSkill
- postgres-patternsSkill
- powershellSkill
- project-trackingSkill
- python-patternsSkill
- pytorch-patternsSkill
- react-patternsSkill
- researchSkill
- review-duplicationSkill
- security-reviewSkill
- seoSkill
- soap-webservicesSkill
- springboot-patternsSkill
- tdd-workflowSkill
- unitySkill
- web-accessibilitySkill
The file
We split this skill into the rules it gives an agent
12 rules. 0 are common, 6 are distinctive, and 6 are very specific to this project.
0
Common
Most of the 12 edited versions we read keep these.
6
Distinctive
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 155
Run route handlers and pages on the Node.js runtime unless a specific deployment constraint says otherwise.
- Distinctive: line 215
Default to none. A doc comment is usually a sign that the code failed to explain itself.
- Distinctive: line 220
When one is still genuinely needed, the prose is capped at five lines and is usually one.
- Very specific: line 272
Every 'use client' sits at the smallest leaf that needs it.
- Very specific: line 273
Every fetch declares a revalidate window, a cache tag, or no-store.
- Very specific: line 274
Every slow region has a Suspense boundary with a real skeleton, and every route has loading.tsx or an equivalent.
- Distinctive: line 275
Every mutation is a Server Action that invalidates the caches it dirties.
- Distinctive: line 276
Every route handler parses its input through a schema and returns a meaningful status code.
- Distinctive: line 277
Every dynamic route derives its metadata from its own data.
- Very specific: line 278
Every image goes through next/image with explicit dimensions, and above-the-fold images set priority.
- Distinctive: line 279
Every heavy client-only module is loaded dynamically.
- Very specific: line 281
No doc comment restates a signature, and every recoverable error is documented with @throws.
“Common” is measured: kept by at least 6 in 10 of the 12 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Next.js App Router Patterns
Architecture rules for Next.js applications built on the App Router, from the Server and Client Component split down to caching, mutations, and dev-server tuning. Every rule here is about where code runs and when its output goes stale.
Baseline: current stable Next.js on the App Router, meaning Next.js 16 or newer, where Turbopack is the default dev
bundler and params and searchParams arrive as promises.
When to activate
- Building or reviewing any route, layout, or component in an
app/directory. - Deciding whether a component belongs on the server or the client.
- Choosing a caching or revalidation strategy for fetched data.
- Adding a Server Action, a route handler, or per-route metadata.
- Migrating a Pages Router application to the App Router.
- Diagnosing a slow
next devstart or a slow hot update. - Fixing a Core Web Vitals regression in a Next.js app. This skill owns that work.
When not to activate
- Framework-agnostic React work: component composition, hooks, forms, animation. Use
react-patterns. - Visual direction, typography, and composition decisions. Use
frontend-design. - Token architecture and theming. Use
design-system. - Keyboard, focus, ARIA, and contrast requirements. Use
web-accessibility. - Titles, meta descriptions, structured data, and keyword mapping. Use
seo. - Profiling the server code and data access behind a slow route. Use
performance-optimization. - Layering, error responses, logging, and shutdown inside a route handler. Use
node-backend-patterns.
Reference map
| Task | Open |
| Server and Client split, streaming, caching layers | references/rendering-and-data.md |
| File conventions, parallel and intercepting routes, route handlers, metadata | references/routing.md |
| Server Actions, form mutations, revalidation | references/server-actions.md |
| Images, bundle splitting, Turbopack, bundle analysis | references/performance-and-tooling.md |
Keep components on the server until interactivity forces otherwise
A Server Component ships no JavaScript to the browser and can reach the database directly. Add 'use client' only at
the leaf that needs state, an effect, or a DOM event handler, then keep that leaf small.
// PASS: server parent fetches, client leaf handles the click
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const product = await db.product.findUnique({ where: { id } })
return <ProductDetail product={product}><AddToCartButton productId={id} /></ProductDetail>
}
// FAIL: the whole page becomes a client bundle for one button
'use client'
export default function ProductPage({ id }: { id: string }) {
const [product, setProduct] = useState<Product | null>(null)
useEffect(() => { fetch(`/api/products/${id}`).then(r => r.json()).then(setProduct) }, [id])
return <ProductDetail product={product} />
}State the cache behaviour on every fetch
An unannotated fetch leaves the freshness of the page to a default that shifts between versions. Say what you mean: a revalidate window, a cache tag you can invalidate, or no store at all.
// PASS: the intent is readable at the call site
const res = await fetch(`${process.env.API_URL}/products`, { next: { revalidate: 3600, tags: ['products'] } })
// FAIL: nothing here says whether this page is static, ISR, or dynamic
const res = await fetch(`${process.env.API_URL}/products`)Stream slow regions behind their own Suspense boundary
Blocking a whole route on its slowest query wastes the fast data. Render what you have, and let each slow region arrive on its own with a real skeleton.
// PASS: header renders immediately, reviews stream in
<ProductHeader product={product} />
<Suspense fallback={<ReviewsSkeleton />}>
<Reviews productId={id} />
</Suspense>
// FAIL: the page waits for the slowest call before anything paints
const [product, reviews] = await Promise.all([getProduct(id), getReviews(id)])
return <ProductDetail product={product} reviews={reviews} />Mutate through Server Actions, not client fetch calls
A Server Action runs on the server, works without client JavaScript, and invalidates its own caches inside the same
function. A client fetch to your own route handler gives up all three.
// PASS: mutation and invalidation live together
'use server'
export async function addToCart(productId: string) {
const parsed = addToCartSchema.safeParse({ productId })
if (!parsed.success) return { error: 'Invalid product' }
await db.cart.create({ data: parsed.data })
revalidateTag('cart')
return { success: true }
}
// FAIL: a client round trip that leaves the cache stale
const handleClick = () => fetch('/api/cart', { method: 'POST', body: JSON.stringify({ productId }) })Validate and type every route handler boundary
A route handler is a public HTTP endpoint. Parse the body and the search params through a schema, hand the work to a
service, and return every error through the shared problem+json handler. The service layering and
toProblemResponse are owned by node-backend-patterns, which answers a failed schema with 422.
// PASS: parsed input, rule in a service, errors through the shared problem+json handler
export async function POST(request: NextRequest) {
try {
const input = createProductSchema.parse(await request.json())
return NextResponse.json(await productService.create(input), { status: 201 })
} catch (error) {
return toProblemResponse(error, request.nextUrl.pathname)
}
}
// FAIL: unvalidated body written straight to the database, always 200
export async function POST(request: NextRequest) {
return NextResponse.json(await db.product.create({ data: await request.json() }))
}Run route handlers and pages on the Node.js runtime unless a specific deployment constraint says otherwise. It is the default and it supports the full API surface most database drivers and SDKs need.
Generate metadata from the same data the page renders
Hardcoded metadata in a dynamic route means every product shares one title. Derive it with generateMetadata, and
pre-render the known set with generateStaticParams.
// PASS: title and description follow the record
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const product = await getProduct((await params).slug)
return { title: product.name, description: product.description }
}
// FAIL: one title for every product in the catalogue
export const metadata = { title: 'Product', description: 'A product page' }Serve images through next/image and split heavy client modules
next/image handles format negotiation, responsive sizing, and lazy loading, and reserves layout space so the page
does not shift. Anything heavy and below the fold loads dynamically instead of riding in the first bundle.
// PASS: sized, prioritised above the fold, heavy chart deferred
<Image src={product.image} alt={product.name} width={1200} height={630} priority />
const Chart = dynamic(() => import('./RevenueChart'))
// FAIL: unsized raw tag plus a charting library in the entry bundle
<img src={product.image} />
import { RevenueChart } from './RevenueChart'Develop on Turbopack
Turbopack is the default next dev bundler and keeps a filesystem cache, so a restart reuses previous work. Fall back
to webpack only to work around a specific bug, and record why.
next devnext dev --webpackThe first command is the normal path. The second is the escape hatch, and a project that needs it permanently has a plugin problem worth fixing rather than a default worth changing.
Doc Comments
Default to none. A doc comment is usually a sign that the code failed to explain itself. Before writing one, extract the unclear block into a well-named function, rename the parameters so they carry their own meaning, and tighten the types. Do that first and most doc comments have nothing left to say, which is the outcome you want. Code that explains itself cannot go stale, a comment can.
When one is still genuinely needed, the prose is capped at five lines and is usually one. Every tag line is capped at
one line, @param and @returns and @throws alike, and only appears when it genuinely adds something: if the note
does not fit on a single line, shorten it or drop the tag. Four rules decide what goes in.
- Prose. One sentence saying what it does, then only what a caller cannot infer from the signature. Nothing more.
@paramonly when the name and the type do not already convey it, meaning units, nullability, a valid range, or who owns the argument afterwards.@param userId - The user identifieris noise, delete it, and never restate a type TypeScript already declares.@returnsonly when it is non-obvious.@throwsalways, for every error a caller can act on. TypeScript keeps throws out of the signature, so this one is genuinely contract rather than decoration.
Going past the five-line prose cap is allowed only when the contract genuinely cannot be stated in fewer lines, for example a documented state machine, an ordering requirement, or a concurrency guarantee. It is an exception you justify in review, not a budget to spend. The one-line cap on a tag line has no exception at all: shorten it or delete it.
// PASS: one sentence, then only what the signature cannot say
/**
* Creates a product and revalidates every cached listing that shows it.
*
* @returns `{ error }` when the submitted form fails validation, never a thrown error
*/
export async function createProduct(formData: FormData): Promise<CreateProductResult> { ... }
// FAIL: restates the signature and the file name
/**
* Server action that creates a product.
*
* @param formData - The form data
* @returns The result
*/
export async function createProduct(formData: FormData): Promise<CreateProductResult> { ... }Related skills
react-patternsfor React composition, hooks, forms, and animation that do not depend on Next.js.frontend-designfor visual direction and composition.design-systemfor tokens, theming, and styling architecture.web-accessibilityfor keyboard, focus, ARIA, and contrast requirements.seofor titles, structured data, and keyword mapping behindgenerateMetadata.performance-optimizationfor profiling server code and data access. Core Web Vitals work stays here.api-designfor the contract shape of route handlers exposed to other clients.
Checklist
- Every
'use client'sits at the smallest leaf that needs it. - Every fetch declares a revalidate window, a cache tag, or
no-store. - Every slow region has a Suspense boundary with a real skeleton, and every route has
loading.tsxor an equivalent. - Every mutation is a Server Action that invalidates the caches it dirties.
- Every route handler parses its input through a schema and returns a meaningful status code.
- Every dynamic route derives its metadata from its own data.
- Every image goes through
next/imagewith explicit dimensions, and above-the-fold images setpriority. - Every heavy client-only module is loaded dynamically.
next devruns on Turbopack, with any webpack fallback justified in writing.- No doc comment restates a signature, and every recoverable error is documented with
@throws.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

