
Claude Code Mastery
13 partsTL;DR
A practical guide to using Claude Code in Next.js projects. CLAUDE.md config for App Router, common workflows, sub-agents, MCP servers, and TypeScript tips that actually save time.
Next.js is the most common framework people use with Claude Code. App Router, server components, API routes, TypeScript everywhere. The combination is natural. But most developers drop Claude into a Next.js project and immediately start fighting it.
Wrong file conventions. Client components where server components should be. Tailwind classes that don't match your config. Routes that don't follow your patterns.
The fix isn't better prompts. It's better project configuration. Here's how to set up Claude Code so it actually understands your Next.js project.
If you already have Claude Code installed, skip to the CLAUDE.md section. If not, the setup takes about 60 seconds.
# Install Claude Code globally
npm install -g @anthropic-ai/claude-code
# Navigate to your Next.js project
cd your-nextjs-app
# Start Claude Code
claude
Claude Code indexes your project on first run. For a typical Next.js app, this takes a few seconds. It reads your package.json, tsconfig.json, next.config.ts, tailwind.config.ts, and the full directory tree. It understands your project before you type a single prompt.
The key thing most people miss: Claude Code works best when it has context about your conventions. That's where CLAUDE.md comes in.
CLAUDE.md is a markdown file at the root of your project that Claude Code reads automatically at the start of every session. Think of it as a briefing document. It tells Claude how your project works, what conventions to follow, and what to avoid.
Here's a production-ready CLAUDE.md for a Next.js App Router project:
# Project Name
Next.js 15 app with App Router, TypeScript, Tailwind CSS, and Prisma.
## Stack
- Next.js 15 (App Router, Server Components by default)
- React 19
- TypeScript (strict mode)
- Tailwind CSS v4
- Prisma + PostgreSQL
- NextAuth.js v5 for authentication
## Architecture
app/ # App Router pages and layouts
(marketing)/ # Route group for public pages
(dashboard)/ # Route group for authenticated pages
api/ # API route handlers
components/
ui/ # Reusable UI primitives (Button, Card, Input)
features/ # Feature-specific components
lib/
db.ts # Prisma client singleton
auth.ts # NextAuth config
utils.ts # Shared utilities
validations/ # Zod schemas
## Conventions
- Server Components by default. Only add "use client" when you need
interactivity, browser APIs, or React hooks.
- All data fetching happens in Server Components or Server Actions.
- API routes use route handlers (route.ts), not pages/api.
- Validate all inputs with Zod schemas from lib/validations/.
- Use next/image for all images. Never use raw <img> tags.
- Use next/link for all internal navigation.
- CSS: Tailwind utility classes only. No CSS modules, no styled-components.
- File naming: kebab-case for files, PascalCase for components.
## Component Patterns
- Pages export default async function (Server Component)
- Client components go in separate files with "use client" directive
- Shared layouts use layout.tsx with children prop
- Loading states use loading.tsx (Suspense boundary)
- Error boundaries use error.tsx with "use client"
## Testing
- Vitest for unit tests
- Playwright for e2e tests
- Run: npm run test (unit), npm run test:e2e (e2e)
- All new features need at least one test
## Common Gotchas
- Don't import server-only code in client components
- Don't use useState/useEffect in server components
- Always handle loading and error states
- Use dynamic imports for heavy client components
- Environment variables: NEXT_PUBLIC_ prefix for client-side access
Adapt this to your actual stack. The key sections are Architecture (so Claude knows where files go), Conventions (so it follows your patterns), and Common Gotchas (so it doesn't make mistakes you've already solved).
You can also create nested CLAUDE.md files. Drop one in app/api/ with API-specific conventions. Drop one in components/ui/ with component patterns. Claude reads the nearest CLAUDE.md relative to the files it's working on.
This is the most frequent task. Tell Claude what the page should do and it handles the App Router conventions.
Add a /pricing page with three tiers (Free, Pro, Enterprise).
Use the existing Card component from components/ui.
Server component, no client-side state needed.
Claude creates app/pricing/page.tsx with proper metadata exports, the right imports, and follows your Tailwind patterns. It knows to use generateMetadata for SEO because it read your other pages.
For dynamic routes:
Add a blog detail page at /blog/[slug].
Fetch the post from the database using the slug param.
Include generateStaticParams for the 20 most recent posts.
Add a loading.tsx skeleton and error.tsx boundary.
Claude generates all four files: page.tsx, loading.tsx, error.tsx, and updates any shared types. It uses generateStaticParams correctly because your CLAUDE.md says "App Router."
Create a POST /api/webhooks/stripe route handler that verifies
the Stripe signature, handles checkout.session.completed events,
and updates the user's subscription status in the database.
Claude creates app/api/webhooks/stripe/route.ts with proper Next.js route handler syntax. It uses NextRequest, returns NextResponse, handles the raw body correctly for Stripe signature verification, and follows your Prisma patterns.
The important detail: Claude knows the difference between Pages Router API routes (pages/api/) and App Router route handlers (app/api/.../route.ts). If your CLAUDE.md says App Router, it won't generate the wrong format.
Create a DataTable component that takes generic typed data,
supports sorting, pagination, and column filtering.
Server-side rendering for the initial data, client-side
interactivity for sort/filter/paginate.
Claude splits this correctly: a server component wrapper that fetches data and passes it to a client component that handles interactivity. It adds "use client" only to the interactive part. It types the generic properly with TypeScript.
For simpler components:
Build a command palette component (Cmd+K). Search across pages,
blog posts, and docs. Use the existing search index from
lib/search.ts.
Claude creates the client component with proper keyboard event handling, focus management, and accessibility attributes. It imports from your existing code rather than reinventing things.
Get the weekly deep dive
Tutorials on Claude Code, AI agents, and dev tools - delivered free every week.
Claude Code supports sub-agents - spawning focused agents for parallel work. This is powerful for full-stack Next.js projects where frontend and backend changes are independent.
When you have a feature that touches both the API layer and the UI, tell Claude to parallelize:
Build a user settings page.
For the backend:
- Create a GET and PATCH /api/settings route handler
- Add a Zod schema for settings validation
- Write a Prisma query for updating user preferences
For the frontend:
- Create app/(dashboard)/settings/page.tsx
- Build a SettingsForm client component with react-hook-form
- Add optimistic updates with useOptimistic
- Include loading.tsx and error.tsx
Claude spawns sub-agents: one handles the API routes and database layer, another builds the UI components. They work in parallel, and Claude coordinates the shared types between them.
MCP servers extend Claude Code's capabilities beyond reading and writing files. Here are the ones that matter for Next.js development.
If you use Prisma, the Prisma MCP server lets Claude query your database directly. Instead of guessing at your schema, it reads it. Instead of writing queries blind, it can test them.
{
"mcpServers": {
"prisma": {
"command": "npx",
"args": ["prisma-mcp-server"]
}
}
}
Claude can now inspect your schema, run test queries, and verify that its Prisma code actually works against your database.
The Playwright MCP server lets Claude interact with your running dev server. It can navigate pages, click buttons, fill forms, and take screenshots.
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@anthropic-ai/mcp-playwright"]
}
}
}
This is useful for:
Claude Code already has filesystem and git capabilities built in. No MCP server needed. It can read files, write files, run shell commands, and commit changes. For Next.js specifically, this means it can:
npm run build to verify no TypeScript errorsnpm run lint to check ESLint rulesnext build output for route analysisThe fetch MCP server lets Claude make HTTP requests to your running dev server. Test your API routes without leaving the terminal.
{
"mcpServers": {
"fetch": {
"command": "npx",
"args": ["@anthropic-ai/mcp-fetch"]
}
}
}
Start your dev server, tell Claude to hit your endpoints, and it verifies the responses match expectations. Faster feedback loop than writing test files for exploratory work.
Enable strict mode in tsconfig.json. Claude Code works significantly better with strict TypeScript because the type errors give it clear signals about what's wrong.
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true
}
}
When Claude writes code that violates a type constraint, it sees the error immediately and fixes it. Without strict mode, subtle bugs slip through.
Add a section to CLAUDE.md about how you handle types:
## Type Patterns
- API responses use shared types from lib/types/api.ts
- Form data validated with Zod, inferred types with z.infer<typeof schema>
- Database types auto-generated by Prisma (never edit manually)
- Component props defined inline for simple cases, extracted to
types/ for shared ones
- Use satisfies for type-safe object literals
- Prefer Record<string, T> over {[key: string]: T}
This prevents Claude from defining types in random places or using inconsistent patterns.
The server/client boundary in Next.js is where most type bugs live. Claude handles this well if you're explicit about the pattern:
## Server/Client Boundary
- Server Components receive data as props from parent server components
or fetch it directly. No "use client" unless absolutely needed.
- Client Components receive serializable props only. No passing
functions, classes, or Maps across the boundary.
- Server Actions are defined with "use server" and accept FormData
or serializable arguments.
- Use separate type files for server-only and shared types.
Configure path aliases in your tsconfig.json so Claude uses clean imports:
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"],
"@/components/*": ["./src/components/*"],
"@/lib/*": ["./src/lib/*"]
}
}
}
Claude picks these up automatically and uses @/components/Button instead of ../../../components/Button. Cleaner code, fewer merge conflicts.
One of the most underused workflows: tell Claude to run next build after making changes. The build output catches:
Run next build and fix any errors.
Claude iterates until the build passes. This single command catches more bugs than most manual review processes.
Here's a real workflow. You want to add a dashboard page with charts and data tables.
Build a /dashboard page that shows:
- Monthly revenue chart (line chart)
- Recent transactions table (sortable, paginated)
- KPI cards at the top (revenue, users, conversion rate)
Use the existing Prisma schema for transactions.
Chart library: recharts. Already installed.
This needs to be a mix of server and client components.
next build to verify everything compiles/dashboard and takes a screenshot for visual verificationThe whole thing takes minutes. Not hours. And it follows your patterns because you told it your patterns.
Do I need Claude Max or does Pro work?
Both work. Max gives you more usage and access to Opus, which handles complex multi-file changes better. Pro with Sonnet is fine for everyday Next.js work. Use Opus for large refactors, architectural changes, or when sub-agents are involved.
Does Claude Code work with Pages Router?
Yes. Put "Pages Router" in your CLAUDE.md and it generates pages/ directory files, getServerSideProps, getStaticProps, and pages/api/ routes. But honestly, if you're starting a new project, use App Router. Claude Code handles it better because the conventions are more explicit.
How does it handle next/image and next/font?
Well, as long as you specify it in CLAUDE.md. Tell it which image loader you use, whether you have a custom next.config.ts for remote patterns, and which fonts you've set up. Claude follows the config.
Can it set up a Next.js project from scratch?
Yes. npx create-next-app@latest with your preferred options, then Claude can scaffold the entire project structure: authentication, database, layouts, components, the works. But it's more effective on existing projects where it has context to match.
What about Next.js middleware?
Claude handles middleware well. Specify in CLAUDE.md that you use middleware for auth redirects, rate limiting, or whatever your case is, and it generates middleware.ts at the root with the right matcher config.
How do I prevent Claude from adding "use client" everywhere?
Put it in your CLAUDE.md: "Server Components by default. Only add 'use client' when you need interactivity, browser APIs, or React hooks." Claude follows this consistently. If it adds "use client" unnecessarily, point it out once and it corrects.
Does Claude understand Next.js caching and revalidation?
Yes. It generates revalidatePath, revalidateTag, and fetch cache options correctly. If you use ISR, specify your revalidation strategy in CLAUDE.md so it matches your patterns.
What if my project uses a monorepo (Turborepo)?
Create a CLAUDE.md at the monorepo root describing the workspace structure, plus one in each app/package with specific conventions. Claude reads the nearest one relative to the files it's editing. This works well for apps/web, apps/api, packages/ui patterns.
Technical content at the intersection of AI and development. Building with AI agents, Claude Code, and modern dev tools - then showing you exactly how it works.
Anthropic's agentic coding CLI. Runs in your terminal, edits files autonomously, spawns sub-agents, and maintains memory...
View ToolHigh-performance code editor built in Rust with native AI integration. Sub-millisecond input latency. Built-in assistant...
View ToolNew tutorials, open-source projects, and deep dives on coding agents - delivered weekly.
AI app builder - describe what you want, get a deployed full-stack app with React, Supabase, and auth. No coding requi...
Install Claude Code, configure your first project, and start shipping code with AI in under 5 minutes.
Getting StartedConfigure Claude Code for maximum productivity -- CLAUDE.md, sub-agents, MCP servers, and autonomous workflows.
AI AgentsInstall the dd CLI and scaffold your first AI-powered app in under a minute.
Getting Started
Try out GitKraken here: https://gitkraken.cello.so/myw3K67IkCr to get 50% GitKraken Pro. In this video, we explore GitKraken, a robust Git GUI that not only visualizes your Git repository...

Creating a Consistent and Beautiful UI for Your AI Application In this video, learn a simple yet effective method to develop a consistent and professional UI design for your AI application....

In this video, I demonstrate Claude Code, a tool by Anthropic currently in limited research preview. This enables developers to delegate tasks directly from the terminal. I walk through installatio...

Aider is open source and works with any model. Claude Code is Anthropic's commercial agent. Here is how they compare for...

A practical guide to building Next.js apps using Claude Code, Cursor, and the modern TypeScript AI stack.

Claude Code runs in your terminal. Cursor runs in an IDE. Both write TypeScript. Here is how to pick the right one.