Skip to content

The Claude Code setup for a Next.js app

The full Claude Code setup for a Next.js repo: instructions, path-scoped rules, skills, subagents, guard hooks and MCP. What goes where, with real files.

Updated · 12 min read

A good Claude Code setup is mostly about where each instruction lives. Facts Claude needs on every task go in one instruction file: CLAUDE.md, or AGENTS.md when other agents share the repo. Conventions for one folder go in a path-scoped rule. Procedures go in skills. Narrow jobs go to subagents. Anything that must never happen goes in a hook.

Get the placement right and your agent forgets less. Get it wrong and you get a 600-line CLAUDE.md it half-reads.

This page is the whole setup on one page, with real files from a generated Next.js repo. Each section links to a deeper guide.

The setup at a glance

LayerWhereWhen it loadsUse it forGuide
InstructionsAGENTS.md, imported by .claude/rules/agents-md.md (or a CLAUDE.md)Every session, in fullStack, commands, repo-wide rules, pointersCLAUDE.md template
Rules.claude/rules/*.mdEvery session, or when Claude touches a matching fileConventions per folderThis page
Skills.claude/skills/<name>/SKILL.mdDescription always, body when usedRepeated proceduresSkills
Subagents.claude/agents/*.mdWhen spawned, in their own contextReviewers, auditors, read-only rolesSubagents
Hooks.claude/settings.json + scripts in .agents/hooks/On the event. No context costThings that must never happenHooks
MCP servers.mcp.jsonTool names at startTalking to Stripe, Neon, SentryThis page
Solution docsdocs/solutions/When readKnown mistakes, written down onceThis page

The last row is not a Claude Code feature. It is a folder of markdown files and a line in the instructions that says "read the relevant one first". It works anyway.

The file tree

This is the shape of a repo the generator writes, with the Claude Code parts in full:

my-app/
  AGENTS.md                  # the instructions every agent reads
  .claude/
    settings.json            # hooks, plugin, claudeMdExcludes
    rules/                   # agents-md.md (imports AGENTS.md) + scoped rules
    skills/                  # /slash-command procedures
    agents/                  # subagents with tool lists
  .agents/
    rules/                   # every rule in full
    skills/                  # the same skills, for other agents
    agents/                  # subagent prompts, for other agents
    hooks/                   # guard scripts and run.mjs, shared by every agent
  .mcp.json                  # MCP servers for your batteries
  SETUP.md                   # every env var and where to get it
  docs/
    solutions/               # known problems, solved
    plans/                   # one plan per piece of work
  src/
    app/api/webhooks/stripe/
      AGENTS.md              # that folder's rules, for other agents

Each other agent you pick adds its own folder next to .claude/: .codex/, .cursor/, .github/, .gemini/ and so on. Commit .claude/ (except settings.local.json) and .agents/. Personal tweaks go in settings.local.json and CLAUDE.local.md.

1. Keep the instruction file short

The instruction file loads in full on every request. Anthropic's docs say to target under 200 lines per CLAUDE.md. Longer files cost more context and get followed less.

What belongs in it:

  • The stack and the package manager.
  • The commands to get running.
  • Where things live.
  • Pointers to everything else: rules, skills, subagents, SETUP.md.

What does not:

  • Conventions for one folder. Those are rules.
  • Multi-step procedures. Those are skills.
  • "Never run X." That is a hook.

@path imports help you organize, but imported files still load at launch. They don't save context.

In a repo other agents share, the instructions live in AGENTS.md. Claude Code reads AGENTS.md on its own since v2.1.277, but only when no CLAUDE.md exists in the project or any folder above it. The generated repo doesn't rely on that. It ships no root CLAUDE.md and imports AGENTS.md from a rule:

@../../AGENTS.md

# Claude Code

- `AGENTS.md` at the repo root holds this repo's instructions. The line above imports it.
- Scoped rules load from `.claude/rules/` when you read a file they cover. The nested `AGENTS.md` files hold the same rules for other agents, so `.claude/settings.json` keeps Claude Code from loading them twice.
- Skills are in `.claude/skills/`: run one as `/name`. Subagents are in `.claude/agents/`.
- `.claude/settings.json` runs the guards in `.agents/hooks/` and turns on the Compound Engineering plugin once you trust this folder. If its commands are missing, run `/plugin install compound-engineering@compound-engineering-plugin`.
- Claude-only notes go in this file.
- MCP servers are in `.mcp.json`. Run `/mcp` to sign in to a remote one.

.claude/rules/agents-md.md, as generated.

The generated AGENTS.md runs past 200 lines, and that's a choice. It carries the rules that apply to every file (code style, git, security) in full. As separate unscoped rules they'd load every session anyway. Everything scoped lives in folders and rule files, not in the root.

The full walkthrough, with a CLAUDE.md template for Claude-only repos: CLAUDE.md template. Both files compared: CLAUDE.md vs AGENTS.md.

2. Path-scoped rules

A rule is a markdown file in .claude/rules/. Without frontmatter it loads at session start, like CLAUDE.md. Add a paths list and it loads only when Claude reads, writes or edits a matching file.

That is the trick that keeps a big setup cheap. A rule on src/lib/billing/** costs nothing while Claude edits a marketing page.

Copy this: a path-scoped rule

A generic example. Save as .claude/rules/route-handlers.md:

---
paths:
  - "src/app/api/**/route.ts"
---

# Route handlers

- Parse the request body with a Zod schema before you use it.
- Check the session inside the handler. Never rely on proxy.ts alone.
- Return Response.json(...) with an explicit status code.
- A new handler gets a test for the happy path and the unauthorized path.

How rules behave:

  • paths is the only field Claude Code reads. Anything else in the frontmatter is ignored.
  • Globs work as you expect. src/**/*.tsx, src/components/**, *.{ts,tsx}.
  • Quote globs that start with * or {. YAML reads a bare * as an alias. If the frontmatter fails to parse, Claude Code ignores it and loads the rule everywhere.
  • Subfolders work. All .md files under .claude/rules/ are found, so rules/frontend/ and rules/backend/ are fine.
  • Personal rules go in ~/.claude/rules/ and apply to every project.

A real rule, scoped to the files it governs

This is the deployment rule from a generated Next.js repo. It loads when Claude touches next.config.ts, src/proxy.ts, a route handler or .env.example:

---
paths:
  - next.config.ts
  - vercel.json
  - package.json
  - src/proxy.ts
  - src/app/**/route.ts
  - .env.example
---

# Deployment rules

Target is Vercel. These constraints are what actually breaks builds and
runtimes, in the order they usually break them.

## Before any deploy

Run all four locally and get them green:

```bash
bun run typecheck
bun run lint
bun run test
bun run build
```

A green dev server is not evidence. `next build` type-checks and prerenders
paths that `next dev` never touches.

First 28 of 72 lines of .claude/rules/deployment.md.

The full repo ships 30 rules. Each line shows the files it applies to:

  • admin-access: src/app/(admin)/**, src/components/admin/**, src/lib/admin/actions.ts, src/app/api/admin/**
  • admin-mutations: src/lib/admin/**, src/components/admin/**, scripts/admin/**
  • app-shell: src/app/(app)/**, src/components/app/**, src/components/ui/sidebar.tsx, src/lib/app-shell.ts, src/lib/nav.ts
  • auth-server-boundary: src/lib/auth/**, src/app/api/auth/**, src/app/(better-auth)/**, src/components/auth/**
  • billing-core: src/lib/pricing.ts, src/lib/billing/**, src/app/pricing/**, src/app/(app)/billing/**, src/components/billing/**
  • blog-content: content/**
  • blog-rendering: src/app/blog/**, src/app/sitemap.ts, src/lib/blog/**, src/components/blog/**, src/mdx-components.tsx
  • code-style: every file
  • deployment: next.config.ts, vercel.json, package.json, src/proxy.ts, src/app/**/route.ts, .env.example
  • drizzle-migrations: src/db/**, drizzle/**, drizzle.config.ts
  • drizzle-schema: src/db/**
  • email-sending-discipline: src/lib/email/**, src/app/api/webhooks/resend/**, src/lib/auth/**, src/lib/billing/**
  • event-naming: src/lib/analytics/**, src/app/**, src/components/**
  • git: every file
  • identify-timing: src/lib/analytics/**, src/app/**, src/components/**
  • landing-and-legal: src/lib/site.ts, src/lib/llms.ts, src/app/page.tsx, src/app/(legal)/**, src/app/llms.txt/**, src/components/marketing/**, src/components/site/**
  • neon-connections: src/db/**, src/app/api/**
  • neon-migrations: src/db/**
  • roles-are-server-side: src/app/**, src/components/**, src/lib/auth/**
  • security: every file
  • sentry-capture: src/**, sentry.server.config.ts, sentry.edge.config.ts
  • sentry-no-pii: every file
  • server-truth-and-pii: src/lib/analytics/**, src/app/**, src/components/**
  • stripe-billing-store: src/lib/billing/**, scripts/billing/**
  • stripe-pricing-source-of-truth: src/lib/pricing.ts, src/lib/billing/**, scripts/billing/**
  • stripe-server-boundary: src/lib/billing/**, src/app/api/webhooks/stripe/**, src/app/**
  • stripe-webhook-integrity: src/app/api/webhooks/stripe/**, src/lib/billing/provider.ts, src/lib/billing/webhook.ts
  • testing: tests/**, src/**/*.test.ts, src/**/*.test.tsx
  • tokens-only: src/components/**, src/app/**
  • ui-kit: src/components/**, src/app/**

Seven come from the Next.js stack: code-style, git and security apply to every file, and testing, deployment, ui-kit and landing-and-legal apply to the files they cover. app-shell, billing-core and tokens-only come with auth, payments and the design. The rest come from the batteries. Stripe alone adds four.

How each one reaches Claude: the rules the root AGENTS.md carries in full arrive through the import. Every other rule gets its own .claude/rules/<id>.md, with paths: when it has a scope. Other agents read the same rules from nested AGENTS.md files, and claudeMdExcludes in .claude/settings.json keeps Claude from loading those twice. Cursor gets an .mdc file only for a rule that didn't fit in its AGENTS.md: 20 in this repo. More in Cursor rules for Next.js.

Write rules Claude can check

  • Checkable, not vibes. "Re-read the files you touched before you finish" works. "Write clean code" doesn't.
  • Do, don't, exception. In that order.
  • One topic per file. stripe-webhook-integrity.md, not backend.md.
  • Short. The generated system-manager agent caps rules at roughly 40 lines. Longer than that, it's a solution doc.
  • Scoped by default. An unscoped rule costs context on every task. Make it earn that.

3. Skills for repeated work

A skill is a SKILL.md that becomes a slash command. Claude sees only its description until it runs, so 30 skills cost 30 descriptions, not 30 files.

The generated repo ships 29: /verify, /write-spec, /qa-feature, /deploy-to-vercel and /security-audit from the stack, plus battery ones like /add-plan, /test-webhook, /db-branch and /add-table. /setup walks a fresh clone through SETUP.md.

Each skill lives once in .agents/skills/, the folder most other agents read. Claude Code never reads .agents/, so .claude/skills/ holds a copy. Write one the third time you explain the same procedure. Full guide, with the /verify skill quoted in full: Claude Code skills.

4. Subagents for narrow jobs

A subagent is a separate Claude with its own prompt, tools and context window. It hands back a summary.

The generated repo ships 7 subagents. pr-reviewer reviews a diff against the rules the repo already wrote down. security-auditor hunts leaked keys and missing auth checks. db-inspector runs SELECT and EXPLAIN only. system-manager owns the agent setup itself (AGENTS.md, .agents/ and each agent's folder) and turns repeated corrections into rules.

The rule of thumb: give each one the smallest tool list that does the job. Full guide: Claude Code subagents.

5. Hooks for what must never happen

Rules, skills and the instruction file are all instructions. Claude reads them and decides. A hook is a script Claude Code runs on every matching tool call, whatever Claude decides.

A PreToolUse hook that exits 2 blocks the call. Hooks run before permission checks, so a block holds even with --dangerously-skip-permissions. The generated repo wires 7:

  • auto-lint.ts: PostToolUse on Edit|Write|MultiEdit
  • block-destructive.ts: PreToolUse on Bash
  • enforce-doc-meta.ts: PostToolUse on Edit|Write|MultiEdit
  • enforce-typecheck.ts: PreToolUse on Bash
  • env-leak-detector-write.ts: PostToolUse on Edit|Write|MultiEdit|Bash|Read|Grep
  • env-leak-detector.ts: PreToolUse on Bash|Read|Grep
  • guard-neon-sql.ts: PreToolUse on Bash

Together they block rm -rf, force pushes, DROP TABLE and .env reads, and redact live secrets from output. The scripts live in .agents/hooks/. .claude/settings.json calls them through a launcher, run.mjs, and so do the hook configs of the other agents that run them. A self-test, bun run verify:hooks, proves each one still fires. Full guide with the wiring: Claude Code hooks.

6. MCP servers, only the real ones

MCP servers give Claude tools for outside services. Project servers live in .mcp.json at the repo root, committed so the team gets the same ones. In an interactive session, Claude Code asks for approval before it uses a project server.

The generated repo only lists servers that its batteries actually have:

{
  "mcpServers": {
    "better-auth": {
      "type": "http",
      "url": "https://mcp.better-auth.com/mcp"
    },
    "neon": {
      "type": "http",
      "url": "https://mcp.neon.tech/mcp?readonly=true"
    },
    "posthog": {
      "type": "http",
      "url": "https://mcp.posthog.com/mcp?readonly=true"
    },
    "sentry": {
      "type": "http",
      "url": "https://mcp.sentry.dev/mcp"
    },
    "stripe": {
      "type": "http",
      "url": "https://mcp.stripe.com"
    }
  }
}

.mcp.json, as generated.

Neon and PostHog connect read-only (?readonly=true). Sign in to each with /mcp. Don't add a server you won't use. Every one is another login and another set of tools in the list.

One trap we measured: Claude Code drops an HTTP server from .mcp.json if its entry carries a tools key. The generated file never has one.

7. Solution docs: mistakes written down once

docs/solutions/ holds one problem per file: symptom, cause, fix, how to verify. The example repo is seeded with 74, like idempotent Stripe webhooks, Neon pooled vs direct URLs, and the PostHog identify race.

AGENTS.md tells every agent to read the relevant one before re-solving anything. When you fix something new, write it down. Every seeded doc is public in the cookbook. Start with idempotent Stripe webhooks.

Claude Code best practices for a Next.js repo

DoWhy
Keep the instruction file shortIt loads on every request
Import AGENTS.md instead of copying itOther agents read the same file, and nothing drifts
Scope every folder-specific rule with pathsIt loads only when it applies
Name your Next.js, React and TypeScript majors in a ruleModels trained on older code write older APIs
Write rules for route.ts, proxy.ts and next.config.tsThat is where builds and deploys break
Turn a procedure you explained twice into a skillIt costs one line until used
Gate side-effect skills with disable-model-invocation: trueNo surprise deploys
Give every subagent an explicit tools listLeaving it out grants every tool
Put "never do X" in a PreToolUse hookInstructions are requests, hooks are not
Use $CLAUDE_PROJECT_DIR in hook commandsGuards keep firing after cd
Test hooks after every change to themGuards die without telling you
Commit .claude/, .agents/ and .mcp.jsonThe whole team gets the same agent
Turn a correction you made twice into a ruleTwo is a pattern, one is an accident

The generated code-style rule has a section for this: "Examples online often target older majors. These are the ones installed here." Copy the idea even if you copy nothing else.

Common mistakes

  • The 600-line CLAUDE.md. Everything in one file, all of it loaded on every task, half of it ignored.
  • A CLAUDE.md above the project. It switches off Claude Code's own AGENTS.md loading. Import AGENTS.md from a rule instead.
  • Unscoped rules for everything. Billing rules loading while Claude edits a button.
  • Advice instead of rules. "Be careful with webhooks" gives Claude nothing to check.
  • Guardrails as prose. "Never run git reset --hard" in an instruction file is a wish.
  • Subagents with every tool. The read-only reviewer that can edit.
  • Hooks nobody tested. Wired once, broken since the last refactor.
  • Rules that contradict. Claude picks one at random. Audit the instruction file and .claude/rules/ together.
  • A setup that never changes. If corrections don't turn into rules, the same bug gets fixed twice.

Same setup in other agents

Everything above has a twin in the other agents, and a generated repo writes all of them from one source:

Agent or topicGuide
CodexCodex setup for Next.js: the AGENTS.md chain, $name skills, hooks, subagents, MCP
GitHub CopilotCopilot setup for Next.js: custom agents, hooks, plugin, MCP
CursorCursor rules for Next.js: .mdc rules, hooks, subagents, MCP
Gemini CLI and AntigravityGemini CLI and Antigravity setup
Skills in every agentAgent Skills
Hooks in every agentGuard hooks in every agent

Get the whole setup in one command

That is a lot of files to write by hand. The generator writes them for your stack:

Or click through the builder. Pick from 26 batteries (auth, database, payments, email, analytics, admin, AI), 31 designs, and your coding agents: all 10 are on by default. The Indie SaaS preset gives you 30 rules, 29 skills, 7 subagents, 7 hooks and 74 solution docs, in every agent's format. $99 once, with lifetime updates.

Battery pages show what each one adds: Stripe, Neon. How the layers fit together: the agentic layer. The shared instruction file: AGENTS.md examples.

FAQ

What is the best Claude Code setup for a Next.js project?

A short instruction file as an index, path-scoped rules in .claude/rules/ for each part of the app, skills for repeated procedures, a few subagents with narrow tool lists, and PreToolUse hooks for anything destructive. Commit all of it.

What are path-scoped rules in Claude Code?

Markdown files in .claude/rules/ with a paths list of globs in their frontmatter. They load only when Claude reads, writes or edits a matching file, so they cost no context the rest of the time.

Where do Claude Code rules go?

Project rules go in .claude/rules/ and get committed. Personal rules go in ~/.claude/rules/ and apply to every project on your machine.

How long should CLAUDE.md be?

Anthropic's docs say to target under 200 lines. Move folder-specific conventions into path-scoped rules and procedures into skills.

Does Claude Code read AGENTS.md?

Since v2.1.277 it reads AGENTS.md when no CLAUDE.md or CLAUDE.local.md exists in the working directory or any folder above it. To load it in every case, import it: @AGENTS.md in a CLAUDE.md, or @../../AGENTS.md in a file in .claude/rules/.

Should I commit the .claude folder?

Yes. Commit .claude/settings.json, rules, skills and agents, plus .agents/ if your repo has it, so the team gets the same setup. Keep personal settings in .claude/settings.local.json.

Sources

Tool behavior is from the official docs, checked on October 8, 2026. Tools change. The docs win.