← All posts

How to Set Up AI Coding Rules for a Next.js Project

AI coding rules for a Next.js project belong in a root AGENTS.md: exact commands for lint, typecheck, test, and build, plus the App Router conventions you'd otherwise repeat — Server Components by default, "use client" only at interaction boundaries, data fetching in the right layer. One committed file makes every session start from the same playbook, in Claude Code, Codex CLI, or OpenCode.

Next.js is a good candidate for instruction files precisely because the framework has so many possible ways to do the same thing. An agent will happily render a client component, fetch data inside it, and format a date with new Date() — all legal, all against your grain. The file is where your grain gets written down.

Where Next.js rules belong

  • Root AGENTS.md — commands and cross-cutting conventions. This is the file every session loads, and the one that should answer "how do I run lint here?" before the agent touches package.json.
  • Nested AGENTS.md — for subtrees with their own rules (src/app/admin/AGENTS.md for an admin area, src/lib/db/AGENTS.md for data access). OpenCode and Codex layer nested files over the root file when the agent works in that directory.
  • A thin CLAUDE.md, if you use Claude Code — a few lines: @AGENTS.md plus anything Claude-specific. See CLAUDE.md vs AGENTS.md for why the pointer beats a copy.

A complete Next.js AGENTS.md example

markdown
# Project instructions

## Overview

Next.js 15 App Router (TypeScript, strict mode, `src/` directory).
Postgres via Drizzle ORM, Auth.js for sessions. One deploy target:
Vercel. npm is the package manager — no yarn, no pnpm.

## Commands

- Install: `npm ci`
- Dev server: `npm run dev`
- Lint: `npm run lint`
- Typecheck: `npx tsc --noEmit`
- Unit + integration tests: `npm test` (Vitest)
- End-to-end tests: `npm run test:e2e` (Playwright)
- Production build: `npm run build`

Definition of done: `npm run lint`, `npx tsc --noEmit`, and `npm test`
all pass. CI runs these three on every pull request.

## Architecture

- `src/app/` — routes. Pages are Server Components; they compose UI
  from `src/components/`, never hold business logic.
- `src/server/` — server-only code: queries, auth checks, actions.
  Importing from `src/app/` into this tree is fine; the reverse is not.
- `src/components/` — shared UI. `"use client"` only when the component
  actually uses state, refs, or browser events.
- `src/lib/` — framework-agnostic helpers (dates, formatting, zod
  schemas). No Next.js imports here.

## Code style

- TypeScript strict; no `any` — use `unknown` and narrow.
- Server Actions validate input with zod before touching the database.
- Route handlers (`app/api/**`) return typed error envelopes; never
  leak internal error messages to the client.
- Dates render through `formatDate` in `src/lib/dates.ts` (UTC in,
  localized out) — no inline `toLocaleString`.
- Env access: `process.env.VAR` on the server, `NEXT_PUBLIC_*` only
  for values the browser truly needs. No `env` object spread.

## Testing

- Vitest for units and integration; Playwright for user flows.
- Test user-visible behavior: `getByRole`, not test ids.
- Mock `src/lib/db` in unit tests; the `docker-compose` Postgres is
  integration-test only.
- Every bug fix lands with a regression test.

## Never do

- Do not add dependencies without asking.
- Do not edit `next.config.mjs`, middleware, or auth code unasked.
- Do not commit `.env*` files or real keys — use `.env.example`.
- Do not run `npm run db:push` against the shared dev database.

Copy it, swap the commands for yours, and delete every rule that doesn't apply. The generator has a Next.js preset that scaffolds this shape — commands, package manager, and the App Router conventions filled in — so the blank page never happens.

The commands your file must include

Command Why the agent needs it verbatim
npm ci Lockfile-exact installs; npm install can drift the lockfile and create a phantom diff.
npm run lint Catches its own mistakes before you review them.
npx tsc --noEmit Next.js type-checks in next build, but the agent should learn errors in seconds, not minutes.
npm test The definition-of-done gate. Without it, "well tested" means whatever the agent felt like.
npm run test:e2e Distinguishes a green unit suite from a working page.
npm run build The real check: App Router catches missing "use client", bad imports, and server/client leakage only at build time.

If your scripts differ (pnpm lint:strict, npm run check:all), write those names. The value is fidelity to what actually runs, not to what a Next.js tutorial assumed.

AI coding rules worth encoding for the App Router

These are the Next.js decisions models most often get wrong when left to defaults:

  • Server Components by default. The file should say it explicitly, because the path of least resistance in a chat answer is "use client" at the top of everything — which quietly moves your data fetching to the browser.
  • "use client" only at interaction boundaries. A button with an onClick needs it; a page that renders data does not. Naming the boundary ("components that use state, refs, or browser events") gives the agent a test it can apply.
  • Fetch data in the layer that owns the UI. Page-level await in a Server Component, not a useEffect — and never both.
  • Validate at every server entry point. Server Actions and route handlers get zod schemas; the client form is a courtesy, not a boundary.
  • One date path. Server renders UTC, client hydrizes localized — mixing new Date() renders into JSX causes hydration mismatches that only appear in production. Point at your helper instead.
  • Env vars by direction. process.env.X server-side, NEXT_PUBLIC_X only when the browser needs it — and never the latter for secrets, because it ships in the bundle.

None of these are enforceable by ESLint alone. All of them are one bullet in the instruction file.

Scoping rules to a subtree

When one area has different rules, don't grow the root file — nest:

markdown
# src/app/admin/AGENTS.md — admin area

- Every page checks `requireAdmin()` first; copy the pattern from
  `src/app/admin/layout.tsx`.
- Admin tables paginate server-side with `searchParams`; no client-side
  filtering of full datasets.
- Destructive actions double-confirm and write to `audit_log`.

OpenCode and Codex pick this up when the agent reads in src/app/admin/; Claude Code loads subdirectory files on demand. Root file stays short, the rules stay next to the code, and the diff that changes admin behavior includes the diff that changes admin rules.

Keep the rules true

  1. CI parity — if you rename a script, update the file in the same PR. This is the single most common way instruction files rot.
  2. Verify in a fresh session — restart the agent, then ask: "What are your project instructions, and what would you run before calling this done?" Wrong or vague answer → the file wasn't read; see why agents ignore instructions.
  3. Score it quarterly — the checker grades structure, commands, clarity, safety, size, and portability; the size check catches a root file that's quietly become a novel.
  4. Keep it under ~150 lines — everything after that moves to nested files, per the guidance in how to write a good AGENTS.md.

FAQ

Does Next.js have a native AI rules file?

Next.js itself doesn't ship one — but every mainstream agent runtime does, and they all read the same root file: AGENTS.md (OpenCode, Codex CLI, and Claude Code v2.1.277+) or CLAUDE.md (Claude Code). AGENTS.md is the one that reaches all of them.

Where do I put AI rules in a Next.js src/ project?

The root of the repository — next to package.json and next.config.mjs, not inside src/. Agents start from the repo root, and a file inside src/ may never be discovered. Directory-specific rules go in a nested AGENTS.md inside src/app/... or src/lib/....

Should Client Component rules live in a separate file?

Not usually. "use client" policy is a three-line convention that belongs with the rest of your style rules. Reach for a nested file when a whole area differs — a charting dashboard where most components are clients, for instance.

How is this different from eslint-plugin-next?

The plugin enforces mechanical rules after the fact (images, hooks, scripts). The instruction file covers judgment: where data fetching happens, what gets validated where, when to stop and ask. Use both — the lint rule catches violations, the file prevents the wrong architecture in the first place.

Start here

Copy the example, adjust six commands, delete what doesn't apply — or generate the whole file from a Next.js preset in about a minute, entirely in your browser. Then paste it into the checker and see if it clears 80 before you commit it.