CLAUDE.md for React/Next.js Projects

React and Next.js move fast. Next.js 13 introduced the App Router. Next.js 14 changed how data fetching works. Next.js 15 brought new caching defaults. If you don’t tell Claude which version and patterns your project uses, it might write code that’s technically valid but completely wrong for your setup.

A well-written CLAUDE.md for a React or Next.js project fixes that immediately. Claude stops suggesting Pages Router patterns in an App Router project. It stops reaching for useEffect when a Server Component would be cleaner. It writes code that actually fits your codebase.

📋 TL;DR
– Always specify whether you’re using App Router or Pages Router — they require completely different patterns
– Include your TypeScript strictness level — it shapes every piece of code Claude writes
– Define your data fetching approach explicitly — this is where Next.js projects diverge most
– Specify your component rules: Client vs Server, file naming, export style
– A complete copy-ready template is included at the bottom of this article

This is part of our complete CLAUDE.md — The Complete Beginner’s Guide (2026). If you’re new to CLAUDE.md, start with What is CLAUDE.md? (And Why You Need One).


Why React/Next.js Projects Need a Detailed CLAUDE.md

React and Next.js have accumulated years of patterns, many of which are now outdated. Without explicit guidance, Claude may default to older approaches:

  • getServerSideProps and getStaticProps instead of Server Components
  • useEffect for data fetching instead of async Server Components
  • Default exports for components instead of named exports
  • Class components instead of functional components
  • React.FC type instead of explicit prop typing

None of these are wrong in isolation, but they might be wrong for your project. Your CLAUDE.md is what makes Claude write code that matches your actual codebase.


Section 1: Framework Version and Router Type

This is the most important thing to get right. App Router and Pages Router are architecturally different. Code written for one doesn’t work in the other.


## Framework
- Next.js 14.2.x — App Router only
- No Pages Router — we migrated away from it in 2024
- React 18 — using Concurrent Features (useTransition, Suspense)

If you’re on Pages Router:


## Framework
- Next.js 13.5.x — Pages Router
- No App Router — we have not migrated yet
- All data fetching via getServerSideProps, getStaticProps, or getStaticPaths
- No Server Components — everything is a Client Component

⚠️ Warning: Never assume Claude knows which router you’re using. A project folder doesn’t reveal this automatically. Specifying it explicitly in CLAUDE.md is non-negotiable for Next.js projects.


Section 2: TypeScript Configuration

TypeScript with strict mode enabled behaves very differently from loose TypeScript. Tell Claude exactly what rules apply.


## TypeScript Rules
- Strict mode enabled (tsconfig.json: "strict": true)
- No `any` — ever. Use `unknown` and narrow the type, or use a proper interface.
- No type assertions (`as SomeType`) without a comment explaining why it's safe
- All function parameters must be typed
- All function return types must be explicit
- Use `type` for unions, intersections, and primitive aliases
- Use `interface` for object shapes that may be extended
- Generic type parameters: use descriptive names (`TEntity`, `TProps`) not single letters

If you’re more relaxed with TypeScript:


## TypeScript Rules
- Strict mode disabled — we're migrating gradually
- Prefer typed code but `any` is acceptable in legacy areas
- New code must have explicit return types
- Avoid type assertions where possible

Section 3: Component Architecture

React projects have strong opinions about component structure. Encoding yours saves constant cleanup.


## Component Rules

### File Structure
- One component per file — no exceptions
- File name matches component name: `UserProfileCard.tsx` for `UserProfileCard`
- Component files in PascalCase: `UserProfileCard.tsx` not `user-profile-card.tsx`

### Exports
- Named exports only — never default exports
- The component and its props type are the only exports from a component file

### Props
- Props interface defined at top of file, named `[ComponentName]Props`
- Example: `interface UserProfileCardProps { userId: string; showAvatar?: boolean }`
- Optional props have a `?` — required props do not have defaults in the interface

### Server vs Client Components (App Router)
- All components are Server Components by default
- Only add `'use client'` when the component needs: useState, useEffect, event listeners,
  browser APIs, or third-party hooks that require client context
- Never add `'use client'` to a component that doesn't need it
- Keep `'use client'` as far down the component tree as possible
- Client Components can import Server Components — but Server Components
  cannot import Client Components directly (pass them as children instead)

### Styling
- Tailwind CSS utility classes only — no inline styles, no CSS modules
- Group Tailwind classes by: layout → spacing → sizing → typography → color → effect
- Use `cn()` from `lib/utils` for conditional class merging (clsx + tailwind-merge)

Section 4: Data Fetching Patterns

This is where Next.js projects diverge most. Your CLAUDE.md needs to make this unambiguous.

For App Router projects:


## Data Fetching Rules (App Router)

### Server Components
- Fetch data directly in Server Components with `async/await`
- Use the `cache()` wrapper for shared data fetching functions
- For request-level caching: `fetch()` with `{ cache: 'no-store' }` or `{ next: { revalidate: 60 } }`

### Client Components
- Use React Query (TanStack Query) for client-side data fetching
- Never use `useEffect` to fetch data — use React Query's `useQuery`
- Mutations via `useMutation` — invalidate queries on success

### Route Handlers
- API routes in `app/api/` handle mutations and third-party webhook endpoints
- Return typed responses using `NextResponse.json()`
- Validate all inputs with Zod before processing

### Never Do
- Never use `getServerSideProps` or `getStaticProps` — those are Pages Router patterns
- Never fetch data in Client Components when a Server Component would work
- Never expose database queries outside of `lib/db/`

For Pages Router projects:


## Data Fetching Rules (Pages Router)
- Use `getServerSideProps` for pages that need fresh data on every request
- Use `getStaticProps` for pages that can be built at build time
- Use `getStaticPaths` with `getStaticProps` for dynamic static pages
- Client-side fetching: SWR for reading, fetch for mutations
- No Server Components — this project uses Pages Router

Section 5: State Management


## State Management

### Local State
- `useState` for simple component-level state
- `useReducer` for complex state with multiple sub-values or state transitions

### Global State
- Zustand for global UI state (modals, sidebar, theme, notifications)
- No Redux — we made a deliberate decision to use Zustand for simplicity
- No React Context for performance-sensitive state — Zustand handles this

### Server State
- React Query for all server state (data from API / database)
- React Query cache is the source of truth for server data
- Don't duplicate server data in Zustand — that causes sync issues

### Form State
- React Hook Form for all forms
- Zod schemas for validation, passed to RHF via `zodResolver`
- No uncontrolled inputs without a good reason

Section 6: File and Folder Structure


## Folder Structure (App Router)

src/

├── app/

│ ├── (auth)/ # Routes requiring authentication

│ │ ├── layout.tsx # Auth layout (includes auth check)

│ │ └── dashboard/

│ │ └── page.tsx

│ ├── (public)/ # Public routes

│ │ └── page.tsx # Home page

│ ├── api/ # API Route Handlers

│ │ └── webhooks/

│ └── layout.tsx # Root layout

├── components/

│ ├── ui/ # Primitive UI components (Button, Input, etc.)

│ └── features/ # Feature-specific components

├── lib/

│ ├── db/ # Prisma client and database utilities

│ │ ├── client.ts # Prisma singleton

│ │ └── queries/ # Query functions by domain

│ ├── auth/ # Auth helpers and configuration

│ └── utils/ # General utilities (cn, formatters, etc.)

├── hooks/ # Custom React hooks

├── stores/ # Zustand stores

├── types/ # Shared TypeScript types

└── config/ # App constants and feature flags



Where things go:
- Database queries: `lib/db/queries/[domain].ts` only — never in components or routes
- Shared types: `types/` — never define the same interface twice
- Zustand stores: one file per domain in `stores/` (e.g. `stores/ui.ts`, `stores/cart.ts`)
- Custom hooks: `hooks/` — name them `use[Noun]` (e.g. `useCart`, `useCurrentUser`)

Section 7: Routing and Metadata


## Routing and Metadata (App Router)
- Dynamic routes: `[param]` for single segments, `[...param]` for catch-all
- All pages export a `generateMetadata` function for SEO (don't use static `metadata`)
- Route groups with `(folder)` don't affect URL — use them to share layouts
- Parallel routes and intercepting routes only when specifically required
- No `next/router` — use `next/navigation` (App Router equivalent)
  - `useRouter()` for programmatic navigation in Client Components
  - `redirect()` for server-side redirects in Server Components and Route Handlers

Section 8: Testing


## Testing
- Testing framework: Vitest
- Component testing: React Testing Library
- Test files: co-located with source files as `[filename].test.tsx`
- Always test: utility functions, custom hooks, and form validation
- Don't test: implementation details, internal state, or third-party library behavior

### Test Patterns
- Prefer `getByRole` and `getByLabelText` over `getByTestId`
- Test user behavior, not component internals
- Mock external dependencies (API calls, Zustand stores) at the module level
- For async tests, use `waitFor` from RTL or `act` for state updates

The Full Template

Copy and use this complete template for your Next.js / React project. Replace everything in brackets.


# [Project Name] — Claude Code Instructions

## Project Overview
[Describe your project: what it does, who uses it, its current stage.]
[Note any priority that shapes technical decisions: speed, security, scale.]

## Tech Stack
- Language: TypeScript [5.x — strict mode / loose mode]
- Framework: Next.js [14 — App Router / 13 — Pages Router]
- Styling: Tailwind CSS v3
- State: [Zustand / Redux Toolkit] + React Query for server state
- Database: [PostgreSQL / MySQL / MongoDB] via [Prisma / Drizzle]
- Auth: [NextAuth.js v5 / Clerk / Supabase Auth]
- Forms: React Hook Form + Zod
- Testing: Vitest + React Testing Library
- Deployment: [Vercel / AWS / other]

## TypeScript Rules
- [Strict / Loose] mode
- [No `any` allowed / `any` in legacy areas only]
- All function params and return types must be explicit

## Component Rules
- Named exports only — no default exports
- One component per file, named `[ComponentName].tsx`
- Props interface: `interface [Name]Props { ... }` at top of file
- `'use client'` only when strictly necessary

## Data Fetching
- [Describe your data fetching approach — Server Components / React Query / SWR]
- [State which patterns are forbidden: e.g. "No useEffect for data fetching"]

## Folder Structure
[Copy the structure section above and customize for your project]

## Commands
- Dev: `npm run dev`
- Test: `npm run test`
- Type check: `npm run typecheck`
- Lint: `npm run lint`
- Build: `npm run build`

## Architecture Notes
[Describe your key architectural decisions in plain English]

## Constraints
- Never use `any` in TypeScript
- Never use inline styles
- Always ask before adding npm packages
- [Add your project-specific constraints]

Common Mistakes in React/Next.js CLAUDE.md Files

Not specifying App Router vs Pages Router. This is the biggest one. Claude will default to the pattern it’s most uncertain about, which may not match yours. Specify it explicitly.

Forgetting to list state management libraries. If you have React Query and Claude doesn’t know, it will suggest useEffect for fetching. If you have Zustand and Claude doesn’t know, it might reach for Redux patterns.

Not defining the 'use client' rule. Without explicit guidance, Claude often adds 'use client' unnecessarily, which prevents Server Component optimizations.

Omitting the testing setup. Claude’s test suggestions vary significantly between Jest, Vitest, and React Testing Library. Specify all three.


Key Takeaways

  • Router type is mandatory** — App Router and Pages Router have incompatible patterns; always specify which one you’re using
  • TypeScript strictness shapes every output** — be explicit about your tsconfig mode
  • Data fetching rules prevent the most common mistakes** — Server Components vs useEffect is where Claude goes wrong most often
  • State management belongs in CLAUDE.md** — if Claude doesn’t know you use Zustand, it’ll reach for something else
  • One component per file and named exports** reduce cleanup time significantly

Next Steps

Return to CLAUDE.md — The Complete Beginner’s Guide (2026) for the full picture.