How to Use Claude Code for Next.js Development
Next.js is the most popular full-stack React framework, and it is also one of the most complex. App Router vs Pages Router, Server Components vs Client Components, server actions, middleware, API routes -- there is a lot to keep straight. Claude Code understands all of these patterns and can generate production-quality Next.js code that follows current best practices. Here is how to use it effectively, with your sessions organized in Beam workspaces.
Why Claude Code + Next.js Is a Perfect Match
Next.js is a framework built on strong conventions. The file-system router dictates where your code lives. Server Components and Client Components have clear boundaries. Data fetching patterns, caching strategies, and rendering modes all follow documented rules. This is exactly the kind of structured environment where Claude Code excels.
Claude Code understands the App Router deeply -- layouts, loading states, error boundaries, route groups, parallel routes, and intercepting routes. It knows the difference between a Server Component and a Client Component and will default to Server Components unless interactivity is required. When you ask it to build a page, it generates proper TypeScript types for all the Next.js-specific APIs like generateMetadata, generateStaticParams, and route handler signatures.
Most importantly, it handles the file-system routing convention without confusion. Ask for a dashboard page and it creates the file at app/dashboard/page.tsx, not in some arbitrary location. Ask for an API route and it creates app/api/[resource]/route.ts with the correct HTTP method exports. This structural awareness means less time correcting file placements and more time building features.
Your Next.js Development Workspace
A Next.js project involves several running processes at once -- your dev server, a database connection, test runners, and Claude Code itself. Beam workspaces let you keep all of these organized in a single window with instant switching between them.
Here is the workspace setup I recommend for Next.js development. Create a workspace called "Next.js App" with these tabs:
- Tab 1: Claude Code -- Your primary AI coding session. This is where you prompt Claude to generate components, pages, and API routes.
- Tab 2: Dev Server -- Run npm run dev here. The Next.js dev server with hot reload lets you see changes instantly.
- Tab 3: Database -- Prisma Studio (npx prisma studio), psql, or your database management tool of choice.
- Tab 4: Tests -- Run npm test -- --watch to continuously validate changes as Claude Code generates them.
- Tab 5: Git -- Stage, commit, and push changes. Review diffs before committing AI-generated code.
Use ⌘⌥⌃T to split your Claude Code tab into a split pane. Put Claude Code on the left and your browser preview on the right. As Claude generates code, you can watch the hot reload reflect changes in real time without switching tabs.
Server Components & The App Router
The App Router introduced a fundamental shift in how Next.js applications are structured. Server Components are the default, Client Components are the exception, and data fetching happens directly inside components with async/await instead of useEffect. Claude Code handles all of this correctly out of the box.
Try this prompt to see it in action:
Example Prompt
"Create a dashboard page with a sidebar layout using the App Router. The sidebar should be a shared layout, the main content area should show user stats fetched server-side."
Claude Code will create the full set of files in the right directories: app/dashboard/layout.tsx for the sidebar layout that wraps all dashboard pages, app/dashboard/page.tsx for the main content with server-side data fetching, app/dashboard/loading.tsx for a Suspense loading state, and app/dashboard/error.tsx with a proper error boundary component.
Notice what it does not do: it does not add 'use client' to the page component. It fetches data with an async Server Component rather than reaching for useEffect and useState. It uses the layout file for shared UI instead of duplicating the sidebar across pages. These are all correct Next.js patterns, and Claude Code applies them by default without you needing to specify them.
Server Actions for Mutations
Server actions are the modern Next.js pattern for handling form submissions and data mutations. They replace the older pattern of creating a separate API route for every mutation. Claude Code understands this pattern thoroughly and generates server actions that follow all the conventions.
Here is a prompt that demonstrates this:
Example Prompt
"Add a server action to create a new project. Include form validation with Zod and optimistic updates."
Claude Code will generate a server action file with the 'use server' directive, a Zod validation schema for the form data, a form component that calls the action, and revalidatePath to refresh the page data after the mutation. It handles the formData extraction correctly, validates the input before touching the database, and returns structured error responses when validation fails. For optimistic updates, it will use the useOptimistic hook in a Client Component wrapper while keeping the actual mutation on the server.
Best Practice
Claude Code follows Next.js best practices: server actions for mutations, Server Components for data fetching, Client Components only when you need interactivity. If you find it adding 'use client' to a component that does not need it, your prompt may be implying client-side behavior. Be specific about what should run on the server.
API Routes & Middleware
While server actions handle most mutations, you still need API routes for webhooks, third-party integrations, and public endpoints. Claude Code generates Next.js API routes using the App Router conventions -- route.ts files with named exports for each HTTP method.
Try this prompt:
Example Prompt
"Create API routes for user CRUD at /api/users with JWT auth middleware."
Claude Code will create app/api/users/route.ts with properly typed GET and POST handlers, and app/api/users/[id]/route.ts with GET, PUT, and DELETE handlers for individual resources. Each handler uses NextResponse correctly, returns proper HTTP status codes, and handles errors gracefully.
For middleware, it creates a middleware.ts file at the project root that intercepts requests before they reach your route handlers. It sets up JWT verification, applies rate limiting headers, configures CORS for API consumers, and uses the matcher config to only run on relevant paths. When edge runtime is appropriate -- such as for lightweight auth checks or redirects -- Claude Code sets the runtime correctly instead of defaulting to Node.js.
Authentication with NextAuth.js
Authentication in Next.js involves multiple moving parts: providers, callbacks, session management, database adapters, and protected routes. Getting all of these pieces to work together is exactly the kind of integration task where Claude Code saves you the most time.
Example Prompt
"Add NextAuth.js with Google and GitHub providers, JWT strategy, and Prisma adapter."
Claude Code will set up the entire authentication flow. It creates the NextAuth route handler at app/api/auth/[...nextauth]/route.ts, configures the Google and GitHub OAuth providers with proper environment variable references, sets up the Prisma adapter so user accounts are persisted to your database, and configures the JWT strategy with custom session callbacks.
It also handles the TypeScript side of things, extending the default Session and JWT types in a types/next-auth.d.ts declaration file so your IDE knows about custom session properties like user.id or user.role. For protected routes, it adds middleware that checks for a valid session and redirects unauthenticated users to the sign-in page, configured to only apply to routes that actually need protection.
Database Integration with Prisma
Prisma is the most common database toolkit in the Next.js ecosystem, and Claude Code handles it seamlessly. From schema design to type-safe queries in Server Components, it generates code that takes full advantage of the Prisma and Next.js integration.
Example Prompt
"Set up Prisma with a PostgreSQL database. Models: User, Project, Task with relations."
Claude Code creates a prisma/schema.prisma file with properly defined models, relations (User has many Projects, Project has many Tasks), and the correct PostgreSQL provider configuration. It generates a lib/prisma.ts client singleton that avoids the common pitfall of creating multiple Prisma Client instances during development. It also creates a prisma/seed.ts file with realistic sample data for local development.
Where this really shines is in the Server Components. Because Prisma queries are type-safe and Server Components run on the server, Claude Code generates components that query the database directly without any API layer in between. Need to add a field? Ask Claude: "Add a migration for adding a 'status' field to the Task model with an enum of TODO, IN_PROGRESS, and DONE." It will update the schema, generate the migration SQL, and update any components that display task data to include the new field.
Deployment
Getting a Next.js application from development to production involves configuration that varies depending on your hosting platform. Claude Code knows the specifics of each major deployment target and generates the right configuration files and optimizations.
Example Prompt
"Configure this app for Vercel deployment with environment variables."
For Vercel, Claude Code creates a .env.example file documenting every required environment variable, sets up vercel.json if custom configuration is needed (rewrites, headers, cron jobs), and ensures your application takes advantage of Vercel-specific features like Incremental Static Regeneration, automatic image optimization via the next/image component, and edge runtime for latency-sensitive routes.
If you prefer self-hosting, prompt Claude Code with "Set up a Dockerfile for self-hosting this Next.js app." It will generate a multi-stage Dockerfile that produces a minimal production image using the standalone output mode, properly handles the .next/static assets, and configures health checks. It also knows to set output: 'standalone' in next.config.js so the build produces a self-contained server.
Memory File: Next.js Conventions
One of the most important things you can do for a long-running Next.js project is create a CLAUDE.md memory file that captures your project's specific conventions. Without this, Claude Code might mix App Router and Pages Router patterns, or suggest a data fetching approach that does not match the rest of your codebase.
Here is what your Next.js memory file should include:
- Router choice -- "This project uses the App Router exclusively. Do not use the Pages Router or getServerSideProps/getStaticProps."
- Data fetching pattern -- "Fetch data in Server Components using async/await. Use server actions for mutations. Do not use API routes for internal data access."
- Auth strategy -- "Authentication is handled by NextAuth.js v5 with JWT strategy and Prisma adapter. Session is accessed via auth() in Server Components."
- Styling approach -- "Use Tailwind CSS for styling. No CSS modules. Use cn() utility for conditional classes."
- Deployment target -- "Deployed to Vercel. Use edge runtime for middleware. ISR for marketing pages. Dynamic rendering for dashboard."
Save this file in your project root and Claude Code will reference it automatically at the start of each session. This prevents inconsistency and keeps every generated file aligned with your architectural decisions. In Beam, you can use the "Install Project Memory" toolbar button to set this up for any project workspace.
Build Next.js Apps Faster
Download Beam and organize your Next.js + Claude Code workflow into clean workspaces with tabs, split panes, and saveable layouts.
Download Beam for macOSSummary
Claude Code and Next.js are a powerful combination. The framework's strong conventions give Claude Code the structure it needs to generate correct, idiomatic code, and Beam keeps your development environment organized so you can move fast without losing context.
- Use Server Components for data fetching -- Claude Code defaults to these correctly
- Use server actions for mutations instead of creating unnecessary API routes
- Set up API routes for webhooks and third-party integrations with proper middleware
- Let Claude Code handle NextAuth.js and Prisma setup -- it knows all the boilerplate
- Create a CLAUDE.md memory file to lock in your project's conventions
- Organize everything in a Beam workspace with dedicated tabs for each concern
The key insight is that Next.js gives Claude Code a well-defined playbook to follow. When you combine that with a clean development environment in Beam and a memory file that captures your project's specific patterns, you get AI-generated code that actually fits your codebase from the first try.