---
id: 23
type: docs
title: "Next.js 16 for Agents: A Verifiable, Production-Ready App Router Guide"
slug: "nextjs-16-agent-first-guide"
canonical_url: "https://docs.phatysd.me/content/nextjs-16-agent-first-guide"
status: published
revision: 3
published_at: "2026-09-19T16:05:12.560Z"
updated_at: "2026-09-19T16:05:12.560Z"
hierarchy_path: "Next.js > App Router > Agent-first development"
topics:
  - "Next.js"
  - "Next.js 16"
  - "App Router"
  - "AI agents"
  - "TypeScript"
  - "Production"
tags:
  - "nextjs"
  - "nextjs-16"
  - "app-router"
  - "agents"
  - "web-development"
related:
  []
---

# Next.js 16 for Agents: A Verifiable, Production-Ready App Router Guide

> Research snapshot: 2026-09-19 (Asia/Bangkok)  
> Repository target: `web-blog`  
> Installed version observed in this repository: `next@16.3.5`  
> Official documentation: [Next.js Docs](https://nextjs.org/docs/app)

This guide is written for coding agents working on a current Next.js App Router codebase. It is not a syntax cheat sheet. The goal is to help an agent identify the correct runtime boundary, understand when data is evaluated, model cache invalidation, protect public interfaces, and verify work before claiming completion.

## 1. Agent summary

When a task arrives in a Next.js App Router project, follow this order:

1. Read `AGENTS.md`, `package.json`, the lockfile, `next.config.*`, the `app/` tree, and the code touched by the task.
2. Confirm the installed version from the lockfile or `node_modules/next/package.json`; do not infer APIs from an old tutorial.
3. Classify the change by boundary: route, Server Component, Client Component, Server Action, Route Handler, data-access layer, or `proxy.ts`.
4. State the data lifecycle explicitly: request-time, prerendered, cached, revalidated, or client-refetched.
5. Enforce authorization in the data-access layer or mutation boundary; do not treat `proxy.ts` as the whole authorization system.
6. Make the smallest scoped change and preserve existing public contracts and data shapes.
7. Run typecheck, lint, available tests, a production build, and a smoke test for affected URLs.
8. Report what was actually verified, separating `Observed`, `Inferred`, and `Unknown` evidence.

If repository documentation conflicts with remembered knowledge, use the installed version and its official documentation as the source of truth.

Next.js also has an [AI Coding Agents guide](https://nextjs.org/docs/app/guides/ai-agents). An agent should read both the repository instructions (`AGENTS.md`) and the framework guide: framework documentation is authoritative for Next.js behavior, while `AGENTS.md` is authoritative for the repository's commands, boundaries, and workflow.

## 2. Version baseline

At this snapshot, the project uses `next@16.3.5` through the `^16.3.5` package range, and the installed package is also `16.3.5`. The guidance here follows the current Next.js 16 App Router documentation as checked on 2026-09-19.

Important Next.js 16 facts:

- Minimum Node.js version: `20.9`.
- Minimum TypeScript version: `5.1`.
- The Next.js 16 release is based on React 19.2.
- Turbopack is the default path for development and production builds.
- App Router uses React Server Components by default.
- `params` and `searchParams` in pages, layouts, and route handlers are asynchronous APIs and must be awaited.
- The newer convention is `proxy.ts` instead of `middleware.ts`; `proxy.ts` runs on the Node.js runtime.
- `next lint` is no longer a Next.js command; invoke ESLint or the repository's lint tool directly.
- `images.domains` is a legacy configuration; use the more restrictive `images.remotePatterns` instead.
- Parallel route slots need `default.js` when a slot may have no matching segment.
- Current `revalidateTag()` usage should provide a cache-life profile; use `updateTag()` in a Server Action when the mutation needs immediate read-your-writes behavior.

Check the [Next.js 16 release](https://nextjs.org/blog/next-16), [Version 16 upgrade guide](https://nextjs.org/docs/app/guides/upgrading/version-16), and [installation requirements](https://nextjs.org/docs/app/getting-started/installation) before upgrading.

## 3. The App Router mental model

Think of `app/` as both a URL tree and a React tree:

```text
app/
├── layout.tsx              # shell shared by the route subtree
├── page.tsx                # UI for the current route
├── loading.tsx             # loading UI for the segment
├── error.tsx               # segment error boundary (must be a Client Component)
├── not-found.tsx           # segment-level 404
├── blog/
│   ├── layout.tsx
│   ├── page.tsx            # /blog
│   └── [slug]/
│       └── page.tsx        # /blog/:slug
└── api/
    └── health/
        └── route.ts        # HTTP endpoint, not a page
proxy.ts                    # request interception at app level
```

Rules an agent should apply:

- A normal folder becomes a route segment when it contains an accessible `page.tsx` or `route.ts`.
- `layout.tsx` wraps its children and can preserve state and navigation across transitions in its subtree.
- `page.tsx` is the public UI for a route.
- `route.ts` is a Web Request handler; a segment cannot have both `page.tsx` and `route.ts` at the same level.
- `(group)` is a route group that organizes files without adding a URL segment.
- `[slug]` is a single dynamic segment, `[...path]` is a catch-all, and `[[...path]]` is an optional catch-all.
- `loading.tsx`, `error.tsx`, `not-found.tsx`, `sitemap.ts`, `robots.ts`, and `opengraph-image.tsx` are framework file conventions, not arbitrary filenames.
- `public/` serves static files; never put secrets or private artifacts there.

See [Project structure](https://nextjs.org/docs/app/getting-started/project-structure), [Layouts and pages](https://nextjs.org/docs/app/getting-started/layouts-and-pages), [Dynamic segments](https://nextjs.org/docs/app/api-reference/file-conventions/dynamic-routes), and [File-system conventions](https://nextjs.org/docs/app/api-reference/file-conventions).

### Dynamic page example for Next.js 16

```tsx
type Props = {
  params: Promise<{ slug: string }>
  searchParams: Promise<{ preview?: string | string[] }>
}

export default async function Page({ params, searchParams }: Props) {
  const { slug } = await params
  const query = await searchParams

  return <Article slug={slug} preview={query.preview === "1"} />
}
```

Do not write `params.slug` or `searchParams.q` without awaiting the promise in this version. When a path is known to Next.js type generation, use the generated helper when appropriate, for example `PageProps<'/blog/[slug]'>`.

## 4. Server Components and Client Components

App Router uses Server Components by default. Keep a component on the server until it genuinely needs a browser API, state, effects, event handlers, or an interactive library.

### Server Components are good for

- Querying a database or calling a service that uses secrets.
- Reading `params`, `searchParams`, headers, and cookies in a server boundary.
- Reducing JavaScript sent to the browser.
- Rendering content, metadata, and layouts that do not need interaction.

### Client Components are good for

- `useState`, `useReducer`, and `useEffect`.
- `onClick`, `onChange`, drag-and-drop, and browser APIs.
- Interactive editors, comboboxes, tabs, modals, and optimistic UI.

Put `'use client'` on the smallest interactive leaf. Do not add it to a whole layout or page automatically: the directive creates a client boundary and increases the code sent to the browser.

```tsx
// app/posts/[slug]/page.tsx — Server Component by default
import LikeButton from "./like-button"

export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const post = await getPost(slug) // server-only data access

  return (
    <article>
      <h1>{post.title}</h1>
      <LikeButton postId={post.id} />
    </article>
  )
}
```

```tsx
// app/posts/[slug]/like-button.tsx — small Client Component leaf
"use client"

export default function LikeButton({ postId }: { postId: number }) {
  // Keep state and event handlers here instead of moving the whole page to the client.
  return <button data-post-id={postId}>Like</button>
}
```

Never pass a database client, secret, non-serializable function, or unnecessary object from server to client. Use a narrow DTO containing only the fields the UI needs, and mark server-only modules so an accidental import fails during the build.

See [Server and Client Components](https://nextjs.org/docs/app/getting-started/server-and-client-components) and [Client Components](https://nextjs.org/docs/app/building-your-application/rendering/client-components).

## 5. Data fetching, rendering, and cache

Before writing a fetch or database query, answer four questions:

1. Is this data shared by every user, or does it depend on a session or cookie?
2. How long may the data be stale?
3. Must a mutation be visible immediately after it completes?
4. Which part should render at request time, and which part should be cached or prerendered?

### Cache Components in Next.js 16

`cacheComponents: true` is an opt-in configuration for Cache Components. Once enabled, cache intentionally with `'use cache'`, `cacheLife()`, and `cacheTag()`. Dynamic code that is not cached runs at request time and should have an appropriate `Suspense` or loading UI.

```ts
// next.config.ts
import type { NextConfig } from "next"

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig
```

```ts
import { cacheLife, cacheTag } from "next/cache"

export async function getPublicPost(slug: string) {
  "use cache"
  cacheLife("hours")
  cacheTag(`post:${slug}`)

  return db.post.findUnique({ where: { slug } })
}
```

Do not put user-specific values such as cookies or sessions into shared cache. Choose between public, remote/shared, and private/user cache deliberately, and verify the deployment adapter before assuming cache survives across instances.

### Invalidation after a mutation

- `cacheTag()` associates a cached query with a tag.
- `revalidateTag(tag, profile)` marks a tag stale and is appropriate for stale-while-revalidate behavior; the profile should express the intended cache lifetime.
- `updateTag(tag)` is used in a Server Action when the same user must immediately read its own write.
- `revalidatePath(path)` is useful when a specific route must be re-rendered; it is not a substitute for a complete cache model.
- If Cache Components are not enabled, inspect the actual fetch and route configuration for the installed version instead of mixing mental models from older Next.js releases.

Example mutation that must show a new item immediately:

```ts
"use server"

import { updateTag } from "next/cache"

export async function createPost(input: FormData) {
  await requireOwner()
  const title = readAndValidateTitle(input)
  const post = await db.post.create({ data: { title } })

  updateTag("posts")
  updateTag(`post:${post.slug}`)
  return { id: post.id }
}
```

Database caching belongs in a server-only module, and invalidation must be designed alongside the mutation rather than added after users report stale data.

See [Caching](https://nextjs.org/docs/app/building-your-application/caching), [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache), [Cache Components migration](https://nextjs.org/docs/app/guides/migrating-to-cache-components), [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife), [`cacheTag`](https://nextjs.org/docs/app/api-reference/functions/cacheTag), [`revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag), and [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag).

## 6. Server Actions and Route Handlers are different boundaries

### Server Actions

Use Server Actions for mutations initiated by UI, such as create, update, or publish forms. Place `'use server'` at the module or function boundary used by the repository. Even when invoked directly by a form, treat the action as a public callable endpoint:

1. Check the session and authorization in every action.
2. Validate and normalize input on the server; client validation is UX only.
3. Apply CSRF and abuse protection required by the auth stack, and rate-limit sensitive work.
4. Do not send stack traces, secrets, or raw database errors to the client.
5. Make writes idempotent or protect retries with unique constraints.
6. Revalidate paths/tags after a write and return serializable state or redirect deliberately.

```ts
"use server"

export async function saveDraft(formData: FormData) {
  const session = await auth()
  if (!session?.user) return { ok: false, message: "Unauthorized" }

  const input = parseDraft(formData)
  if (!input.ok) return input.error

  const draft = await db.transaction(async (tx) => {
    // Enforce authorization and invariants inside the appropriate transaction boundary.
    return tx.draft.create({ data: input.value })
  })

  revalidatePath("/dashboard")
  return { ok: true, id: draft.id }
}
```

### Route Handlers

Use Route Handlers when the application needs an HTTP API such as a webhook, JSON/Markdown export, health check, integration endpoint, or an HTTP method that is not a form mutation. A Route Handler lives in `app/**/route.ts` and receives a Web `Request` and returns a `Response` or `NextResponse`.

```ts
export async function GET(
  request: Request,
  segmentData: { params: Promise<{ slug: string }> },
) {
  const { slug } = await segmentData.params
  const item = await getPublicItem(slug)

  if (!item) return Response.json({ error: "Not found" }, { status: 404 })
  return Response.json({ id: item.id, title: item.title })
}
```

For each Route Handler, define status codes, content type, cache policy, CORS, and error shape explicitly. Do not turn a Server Action into an accidental public API contract, and do not expose an internal database row when the client only needs a public DTO.

See [Server Actions and Mutations](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations), [Forms](https://nextjs.org/docs/app/guides/forms), and [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers).

## 7. `proxy.ts`: request interception, not the authorization layer

In Next.js 16, use `proxy.ts` for logic that must intercept a request before rendering, such as rewrites, redirects, locale routing, request headers, or a coarse authentication redirect.

```ts
import { NextResponse, type NextRequest } from "next/server"

export function proxy(request: NextRequest) {
  const hasSessionCookie = Boolean(request.cookies.get("session"))

  if (!hasSessionCookie && request.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/auth/signin", request.url))
  }

  return NextResponse.next()
}

export const config = {
  matcher: ["/dashboard/:path*"],
}
```

Warnings:

- Keep matchers narrow and test them; do not intercept every URL by default.
- Cookie presence is only a signal. Enforce real session, ownership, and role checks in the Server Action or data layer.
- Avoid expensive database work in the proxy.
- Check runtime compatibility for every imported package because the Next.js 16 proxy convention uses the Node.js runtime.
- When renaming `middleware.ts`, check matchers, imports, tests, and deployment behavior together.

See [Proxy](https://nextjs.org/docs/app/api-reference/file-conventions/proxy) and [Redirecting](https://nextjs.org/docs/app/building-your-application/routing/redirecting).

## 8. Environment variables and security

Rules an agent should remember:

- Treat variables without `NEXT_PUBLIC_` as server-only; never import them into a Client Component.
- `NEXT_PUBLIC_*` values are inlined into the client bundle at build time. They are not secrets, and the value can be frozen to the environment used for the build.
- Keep production secrets in the platform's environment-variable or secret manager, not in git.
- Set environment variables before the build when they must be bundled, and verify runtime variables separately for server code.
- Never print `DATABASE_URL`, OAuth secrets, `AUTH_SECRET`, cookie secrets, or tokens in logs, reports, or stack traces.
- Validate environment variables at startup or the first server boundary with a clear schema and a non-secret error message.
- Public origin, OAuth callback URL, canonical URL, and trusted-host settings must agree across the app, provider, and reverse proxy.

Example server-only environment access:

```ts
import "server-only"

export function databaseUrl() {
  const value = process.env.DATABASE_URL
  if (!value) throw new Error("DATABASE_URL is not configured")
  return value
}
```

With a reverse proxy or CDN, verify the protocol seen by the application, trusted host behavior, forwarded headers, `Secure` cookies, OAuth callback URL, and canonical origin together. Do not fix one redirect URL while leaving the other boundaries inconsistent.

See [Environment Variables](https://nextjs.org/docs/app/guides/environment-variables), [Authentication](https://nextjs.org/docs/app/guides/authentication), and [Data Security](https://nextjs.org/docs/app/guides/data-security).

## 9. SEO, metadata, and agent-readable content

For a public knowledge site, separate three representations:

1. HTML for people and search engines.
2. Metadata, sitemap, and robots files for discovery.
3. JSON and Markdown endpoints for agents and integrations that need a stable contract.

Use the Metadata API or Next.js metadata file conventions:

```ts
import type { Metadata } from "next"

export const metadata: Metadata = {
  title: "Article title",
  description: "Short, accurate description",
  alternates: { canonical: "https://example.com/content/article" },
}
```

Principles for an agent-readable endpoint:

- The canonical URL must be stable and must not change because of unrelated query parameters.
- JSON should include an identifier, type/version, status, timestamps, and a complete `body`.
- Markdown should include parseable metadata such as `slug`, `type`, `revision`, `published_at`, and `updated_at`.
- A missing resource must return a real 404, not a 200 response with an empty body.
- Never expose drafts, archived content, internal IDs, or owner-only fields through public endpoints.
- Add fields backward-compatibly; if a meaning changes, add a contract version or migration note.

See [Metadata](https://nextjs.org/docs/app/getting-started/metadata-and-og-images), [Sitemap](https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap), [Robots](https://nextjs.org/docs/app/api-reference/file-conventions/metadata/robots), and [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers).

## 10. Images, fonts, and external origins

- Use `next/image` when sizing, optimization, and lazy loading are useful.
- Allowlist remote images with the narrowest practical `images.remotePatterns`.
- Do not use `images.domains` for new work; it is a legacy configuration.
- Use `next/font` for controlled font loading and lower layout shift.
- Verify CSP, image hosts, preload behavior, and cache headers after deployment rather than trusting only the development server.

```ts
// next.config.ts
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "images.example.com",
        pathname: "/assets/**",
      },
    ],
  },
}

export default nextConfig
```

See [Image Optimization](https://nextjs.org/docs/app/getting-started/images), [Image component](https://nextjs.org/docs/app/api-reference/components/image), and [Font Optimization](https://nextjs.org/docs/app/getting-started/fonts).

## 11. Testing and production verification

`next build` passing does not prove that authentication, OAuth callbacks, cache invalidation, DNS, TLS, or database migrations work in production. Verify each layer:

### Static checks

```bash
npm run typecheck
npm run lint
npm run build
```

If a script does not exist, inspect `package.json` and the real project configuration before inventing a command. In Next.js 16, do not use `next lint` by default; use the repository's ESLint or Biome command.

### Behavior checks

- An anonymous user can open public pages.
- Protected routes redirect to the correct origin without a loop.
- Invalid input returns a predictable error shape.
- A missing resource returns 404.
- A mutation writes data and reads it back according to the cache policy.
- Public endpoints do not return secrets, drafts, or internal-only fields.
- A dynamic route with `[slug]` awaits `params`.
- The production server starts after the build with the same environment model used in deployment.

### External checks

- Check the public domain, content URL, JSON representation, and Markdown representation.
- Check the TLS certificate and reverse-proxy mode.
- Check the OAuth callback URL as an exact string.
- Check database migrations and SSL connections.
- Check logs without exposing secrets.

Use the repository's E2E tool, such as Playwright or Cypress, for browser behavior. Keep unit and integration tests focused on data access, action validation, route status, and public contracts.

See [Testing](https://nextjs.org/docs/app/guides/testing), [Production Checklist](https://nextjs.org/docs/app/guides/production-checklist), and [Deploying](https://nextjs.org/docs/app/getting-started/deploying).

## 12. Deployment checklist for Heroku or Node hosting

1. Keep the lockfile in the repository so the build uses reproducible dependency versions.
2. Use Node `20.9+` and keep the version consistent across local, CI, and Heroku.
3. Set runtime secrets before start and public environment values before build when they must be bundled.
4. Use `next build` through the project's build script.
5. Use `next start` or the server command defined by the repository.
6. Run database migrations as a release step separate from app start, and make retries safe.
7. Use the platform-provided `PORT`; never hardcode an internal port or mistake a dyno port in logs for a public URL.
8. Align the canonical origin, OAuth callback, trusted host, and proxy headers with the custom HTTPS domain.
9. Enable SSL for a managed Postgres provider and test the connection from the real runtime.
10. After deployment, check health, public pages, authentication, database write/read behavior, logs, and the rollback path.

For this repository, the known commands are `npm run build`, `npm run start`, `npm run lint`, `npm run typecheck`, `npm run db:generate`, `npm run db:migrate`, and `npm run db:seed`. Do not run the seed script in production unless the task explicitly requires it: a seed can create real sample data.

## 13. Migration checklist from older Next.js versions to 16

When an agent finds older code, search for the complete group rather than fixing only the first error:

- `params.` and `searchParams.` in pages, layouts, metadata, and route handlers: convert the types to promises and `await` them.
- `middleware.ts`: evaluate the move to `proxy.ts`, then check matchers and runtime behavior.
- `next lint`: replace it with the repository's ESLint or Biome command.
- `revalidateTag(`: inspect the signature and provide the correct profile or use the API whose semantics match the requirement.
- `images.domains`: replace it with `remotePatterns`.
- Parallel route slots: add `default.js` when a slot may not match.
- `experimental.ppr` and older cache patterns: read the Cache Components migration guide before changing configuration.
- APIs that were synchronous in older versions, including `cookies()`, `headers()`, and `draftMode()`: check the version migration and await the current API.
- Custom servers and adapters: verify Node runtime, build output, and deployment contracts.

Do not perform a global search-and-replace migration without typechecking and building. Some occurrences may be helpers with different types or library boundaries.

## 14. Recommended agent workflow for a new task

### Before editing

```text
Observed:
- package version, route path, current schema, existing scripts

Inferred:
- intended behavior from nearby code and official documentation

Unknown:
- missing acceptance criteria, provider behavior, deployment setting

Plan:
- smallest files and verification checks needed
```

Read sources of truth in this order: `AGENTS.md` → requirement/spec/task → package/config → relevant code → version-matched official docs → tests.

### While editing

- Preserve the Server/Client boundary.
- Do not add a dependency when an existing dependency or standard API is sufficient.
- Validate at the server boundary.
- Use types that express the contract instead of `any`.
- Keep cache policy and invalidation close to the query and mutation.
- Never log secrets or copy production data into fixtures.
- When changing a public contract, update its types, implementation, tests, and docs together.

### Before reporting completion

Report at least:

- Files changed and why.
- Commands actually run and their results.
- URLs or APIs smoke-tested.
- Migrations or environment changes the user must perform.
- Known limitations or `Unknown` items that could not be verified.

## 15. Research source map

Primary sources used for this guide are official Next.js/Vercel documentation and repository documentation:

- [Next.js App Router docs](https://nextjs.org/docs/app)
- [AI Coding Agents](https://nextjs.org/docs/app/guides/ai-agents)
- [Next.js 16 release](https://nextjs.org/blog/next-16)
- [Next.js 16 upgrade guide](https://nextjs.org/docs/app/guides/upgrading/version-16)
- [Installation and system requirements](https://nextjs.org/docs/app/getting-started/installation)
- [Project structure](https://nextjs.org/docs/app/getting-started/project-structure)
- [Layouts and pages](https://nextjs.org/docs/app/getting-started/layouts-and-pages)
- [Dynamic route segments](https://nextjs.org/docs/app/api-reference/file-conventions/dynamic-routes)
- [Server and Client Components](https://nextjs.org/docs/app/getting-started/server-and-client-components)
- [Caching](https://nextjs.org/docs/app/building-your-application/caching)
- [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache)
- [Cache Components migration](https://nextjs.org/docs/app/guides/migrating-to-cache-components)
- [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers)
- [Server Actions and Mutations](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations)
- [Proxy file convention](https://nextjs.org/docs/app/api-reference/file-conventions/proxy)
- [Environment variables](https://nextjs.org/docs/app/guides/environment-variables)
- [Authentication](https://nextjs.org/docs/app/guides/authentication)
- [Data security](https://nextjs.org/docs/app/guides/data-security)
- [Metadata and OG images](https://nextjs.org/docs/app/getting-started/metadata-and-og-images)
- [Testing](https://nextjs.org/docs/app/guides/testing)
- [Production checklist](https://nextjs.org/docs/app/guides/production-checklist)
- [Deploying](https://nextjs.org/docs/app/getting-started/deploying)

Statements using “should”, “recommended”, or “do not” are engineering recommendations synthesized from the official documentation and this repository's context; they are not all hard requirements of the Next.js API.
