Skip to content
spaget

next.js AI agent configuration: the definitive setup

spaget team 8 min read

Next.js is the dominant React framework in 2026, and if you’re building with it, you’re almost certainly using AI coding tools. The combination is excellent — but only if your AI assistant actually understands the nuances of Next.js development.

Without proper configuration, your AI will mix up App Router and Pages Router, suggest outdated patterns, use useEffect where a server component would do, and generate API routes in the wrong directory. With good configuration, it understands your specific Next.js setup and writes code that actually fits.

This guide gives you the complete configuration setup for a modern Next.js project — ready to copy and adapt.

What AI agents get wrong about Next.js by default

Next.js has evolved dramatically. The App Router (introduced in Next.js 13, now dominant in 15) is fundamentally different from the Pages Router. But AI models have training data spanning years of Next.js, so they default to a mix of old and new patterns.

Common AI mistakes in Next.js projects without configuration:

  • Creating pages/ files when you use app/
  • Using getServerSideProps (Pages Router) in App Router projects
  • Adding "use client" to every component by default
  • Generating pages/api/ routes instead of app/api/route.ts
  • Using useRouter from next/router instead of next/navigation
  • Creating _app.tsx wrappers in App Router projects
  • Using React’s useEffect for data fetching instead of async server components

Every one of these is a fixable config problem. The AI doesn’t know you’re using App Router unless you say so.

The base AGENTS.md for a Next.js project

This is the universal context file every AI tool reads:

# Project
[Brief description of what this project does]
# Stack
- Next.js 15 with App Router (NOT Pages Router — never use pages/ directory)
- TypeScript in strict mode
- Tailwind CSS (no CSS modules, no styled-components)
- [Your data layer: Prisma/Drizzle/Supabase/etc.]
- [Your auth: NextAuth.js/Clerk/Auth.js/etc.]
- [Your deployment: Vercel/etc.]
# App Router conventions (critical)
- All routes live in `app/` — never `pages/`
- API routes use `app/api/[route]/route.ts` with `export async function GET/POST/etc.`
- Use `next/navigation` for routing (not `next/router`)
- Import `useRouter` from `next/navigation`, `usePathname` from `next/navigation`
- Dynamic routes: `app/products/[id]/page.tsx` (not `pages/products/[id].tsx`)
# Component conventions
- Server components are the default — no "use client" unless needed
- Add "use client" only when you use: useState, useEffect, useRef, event handlers, browser APIs
- Server components can be async — use `async/await` for data fetching directly
- Never use useEffect for data fetching — fetch in server components or server actions
# Data fetching
- Fetch data in server components using async/await
- Use `cache()` from React for memoization when needed
- Server actions (in `app/actions/`) for mutations
- `use server` directive at top of server action files
- Never fetch data in client components unless truly necessary
# File structure
app/
(auth)/ # Route groups for auth-required routes
api/ # API routes (route.ts files)
[feature]/
page.tsx # Page component
loading.tsx # Loading UI (Suspense boundary)
error.tsx # Error boundary
layout.tsx # Layout (if feature-specific)
components/
ui/ # Reusable UI primitives
[feature]/ # Feature-specific components
lib/
db/ # Database queries and mutations
utils.ts # Utility functions
validations/ # Zod schemas
# Commands
- `pnpm dev` — start development server (localhost:3000)
- `pnpm build` — production build
- `pnpm start` — start production server
- `pnpm lint` — ESLint
- `pnpm check` — TypeScript type check
# Avoid
- Never use `getServerSideProps`, `getStaticProps`, or `getInitialProps`
- Never use `pages/` directory files
- Never use `next/router` — always `next/navigation`
- Never add `"use client"` by default — only when necessary
- Never use `any` type
- Never use inline styles — use Tailwind utilities

Claude Code CLAUDE.md

Layer Claude Code-specific configuration on top:

CLAUDE.md
See AGENTS.md for project conventions.
# Working in this codebase
## Before completing any task
Run the following and fix any errors before declaring done:
- `pnpm lint` — ESLint must pass
- `pnpm check` — TypeScript must compile cleanly
- `pnpm build` — production build must succeed (catches many Next.js-specific errors)
## Next.js-specific guidance
When creating a new page:
1. Create `app/[route]/page.tsx` with a default export
2. If the page needs loading UI, create `app/[route]/loading.tsx`
3. If the page has forms or mutations, create server actions in `app/actions/[feature].ts`
When creating an API route:
1. Create `app/api/[route]/route.ts`
2. Export named functions: `GET`, `POST`, `PUT`, `DELETE`, `PATCH`
3. Use `NextRequest` and `NextResponse` types
4. Always validate input with Zod
When creating a component:
1. Default to server component (no directive needed)
2. Add `"use client"` only if the component uses React hooks or event handlers
3. Co-locate the component file near where it's used unless it's reusable
## Data and mutations
- Database queries go in `lib/db/` — never in components or route handlers
- Server actions go in `app/actions/` with `"use server"` at the top of the file
- Always validate server action inputs with Zod before processing

Cursor rules

For Cursor, use MDC format to target different file types:

.cursor/rules/nextjs.mdc
---
description: "Next.js App Router conventions"
globs: ["app/**/*.tsx", "app/**/*.ts"]
alwaysApply: false
---
This project uses Next.js 15 App Router.
Key rules for app/ directory files:
- Page files (`page.tsx`) are server components by default
- API routes use named exports: `export async function GET(request: NextRequest)`
- Use `next/navigation` for routing, never `next/router`
- Async data fetching is done directly in server components with await
- "use client" is added only when the component requires interactivity
.cursor/rules/server-actions.mdc
---
description: "Server action conventions"
globs: ["app/actions/**/*.ts"]
alwaysApply: false
---
Files in app/actions/ are server action files.
- `"use server"` directive must be at the top of every file in this directory
- All inputs validated with Zod before processing
- Return a typed result: `{ data: T } | { error: string }`
- Never throw — return errors as data

Common patterns to document

Authentication pattern

Add this to your AGENTS.md if using NextAuth.js or Clerk:

# Authentication
Using [NextAuth.js v5 / Clerk].
Protecting routes:
- Route groups in app/(auth)/ are behind auth middleware
- Use `auth()` from `@/lib/auth` to get the session in server components
- Client components use the `useSession()` hook from `next-auth/react`
Never check authentication in page components — use middleware or layout-level auth.

Data fetching pattern

# Data access pattern
Database queries:
- Write query functions in `lib/db/[entity].ts`
- Query functions are async and return typed data
- Use Prisma's generated types for return values
- No raw SQL — use Prisma query builder
Example:
```typescript
// lib/db/users.ts
import { db } from "@/lib/db"
export async function getUserById(id: string) {
return db.user.findUnique({
where: { id },
select: { id: true, name: true, email: true } // always select explicitly
})
}
## Validating your config
After setting up your configuration, test it with a few prompts that typically trip up unconfigured agents:
- "Create a new page that shows a list of users" — should create `app/users/page.tsx` as a server component
- "Add a form to create a new user" — should use a server action, not a client-side API call
- "Create an API endpoint for user authentication" — should create `app/api/auth/route.ts`
- "Add loading state to the users page" — should create `app/users/loading.tsx`
If any of these produce Pages Router patterns or unnecessary client components, the config needs strengthening in that area.
## Using spaget for Next.js configuration
If you're using multiple AI tools on your Next.js project, [spaget](https://app.spaget.ai) lets you maintain one canonical Next.js configuration and export to CLAUDE.md, cursor rules, and copilot-instructions.md simultaneously.
The Next.js template in spaget's template library gives you a starting point — add your project-specific details and export. No account required, [try it here](https://app.spaget.ai).
## The bottom line
A well-configured AI assistant in a Next.js project writes App Router code by default, knows where your data layer lives, understands your auth approach, and respects your TypeScript discipline. An unconfigured one fights the framework half the time.
Copy the AGENTS.md above, fill in your project-specific details, add your stack choices, and your AI assistant will write Next.js code that actually matches how your team builds.
## Further reading
- [AGENTS.md explained: the new standard for AI coding agents](/blog/agents-md-explained)
- [CLAUDE.md explained: configuring Claude Code the right way](/blog/claude-code-claude-md)
- [AI agent configuration best practices for 2026](/blog/ai-agent-configuration-best-practices)
- [How to set up cursor rules: the complete guide](/blog/cursor-rules-guide)