agentleFS
Lukk17Lukk17/agent-standards/.agents/skills/nextjs-app-router-patterns/SKILL.md

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

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.
  • AWSSkill

    tdd

    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

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
  1. Very specific:

    Run route handlers and pages on the Node.js runtime unless a specific deployment constraint says otherwise.

    line 155
  2. Distinctive:

    Default to none. A doc comment is usually a sign that the code failed to explain itself.

    line 215
  3. Distinctive:

    When one is still genuinely needed, the prose is capped at five lines and is usually one.

    line 220
  4. Very specific:

    Every 'use client' sits at the smallest leaf that needs it.

    line 272
  5. Very specific:

    Every fetch declares a revalidate window, a cache tag, or no-store.

    line 273
  6. Very specific:

    Every slow region has a Suspense boundary with a real skeleton, and every route has loading.tsx or an equivalent.

    line 274
  7. Distinctive:

    Every mutation is a Server Action that invalidates the caches it dirties.

    line 275
  8. Distinctive:

    Every route handler parses its input through a schema and returns a meaningful status code.

    line 276
  9. Distinctive:

    Every dynamic route derives its metadata from its own data.

    line 277
  10. Very specific:

    Every image goes through next/image with explicit dimensions, and above-the-fold images set priority.

    line 278
  11. Distinctive:

    Every heavy client-only module is loaded dynamically.

    line 279
  12. Very specific:

    No doc comment restates a signature, and every recoverable error is documented with @throws.

    line 281

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

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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 dev start 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

TaskOpen
Server and Client split, streaming, caching layersreferences/rendering-and-data.md
File conventions, parallel and intercepting routes, route handlers, metadatareferences/routing.md
Server Actions, form mutations, revalidationreferences/server-actions.md
Images, bundle splitting, Turbopack, bundle analysisreferences/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 dev
next dev --webpack

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

  1. Prose. One sentence saying what it does, then only what a caller cannot infer from the signature. Nothing more.
  2. @param only 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 identifier is noise, delete it, and never restate a type TypeScript already declares.
  3. @returns only when it is non-obvious.
  4. @throws always, 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-patterns for React composition, hooks, forms, and animation that do not depend on Next.js.
  • frontend-design for visual direction and composition.
  • design-system for tokens, theming, and styling architecture.
  • web-accessibility for keyboard, focus, ARIA, and contrast requirements.
  • seo for titles, structured data, and keyword mapping behind generateMetadata.
  • performance-optimization for profiling server code and data access. Core Web Vitals work stays here.
  • api-design for 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.tsx or 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/image with explicit dimensions, and above-the-fold images set priority.
  • Every heavy client-only module is loaded dynamically.
  • next dev runs on Turbopack, with any webpack fallback justified in writing.
  • No doc comment restates a signature, and every recoverable error is documented with @throws.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.