Code Kit v5.0 released for CC's new Agent Teams feature.
Claude FastClaude Fast

Claude Code Prompt Templates: 10 Patterns That Produce Production Code

Battle-tested Claude Code prompt templates for React apps, APIs, testing, refactoring, and debugging. Includes why each works and common mistakes to avoid.

Stop configuring. Start shipping.Everything you're reading about and more..
Agentic Orchestration Kit for Claude Code.

The difference between a prompt that produces throwaway code and one that generates production-ready output comes down to specificity. Vague prompts get vague results. These templates encode the specificity that makes Claude Code produce code you'd actually ship.

Each template below includes the prompt itself, why it works (the prompt engineering principle), variations for different contexts, and the mistakes people make when they try something similar without the structure. If you're new to Claude Code, start with the getting started guide first, then come back here with a project to test these on.

Project Scaffolding

Full-Stack Web App

claude "Create a React app with TypeScript and Tailwind CSS. It's a todo app with localStorage persistence. Include: add, edit, delete, mark complete, and filter by status (all/active/completed). Use a single TodoContext for state management. Make it mobile-responsive with min-width 320px support."

Why this works: The prompt specifies the tech stack, data layer, every CRUD operation, state management approach, and responsive breakpoint. Claude doesn't have to guess any of these, so it doesn't make assumptions you'll need to undo later.

Variations:

  • For Next.js: Replace "React app" with "Next.js 15 app using App Router and Server Components where possible"
  • For Vue: Replace the React/TypeScript stack with "Vue 3 with Composition API and TypeScript"
  • For a more complex starting point: Add "Include dark mode toggle, keyboard shortcuts (Ctrl+N for new, Delete to remove), and export/import as JSON"

Common mistakes: Saying "create a todo app" without specifying the tech stack forces Claude to pick defaults that may not match your project. Saying "make it look good" is worse than specifying Tailwind, because "good" is subjective and Claude will waste tokens on styling decisions instead of functionality.

Expected output: 3-5 files including a React component tree, a context provider, TypeScript interfaces for the todo data model, and a responsive Tailwind layout. Runs immediately with npm run dev.

API Backend with Auth

claude "Build an Express.js REST API with JWT authentication. Include: user registration (POST /auth/register), login (POST /auth/login), and a protected endpoint (GET /auth/me). Hash passwords with bcrypt (12 rounds). Use middleware for token verification. Add Zod validation for request bodies. Return consistent JSON error responses with status codes. Include a health check endpoint at GET /health."

Why this works: Explicit endpoint definitions prevent Claude from inventing its own routing structure. Specifying bcrypt rounds, the validation library, and error response format means the output matches your existing project conventions without manual cleanup.

Variations:

  • For Fastify: Replace "Express.js" with "Fastify with @fastify/jwt plugin"
  • For database integration: Add "Use Prisma with PostgreSQL. Include a User model with id, email, passwordHash, createdAt fields"
  • For session-based auth: Replace "JWT authentication" with "express-session with Redis store for session management"

Common mistakes: Omitting error handling requirements means Claude generates the happy path only. You'll get registration and login that work when inputs are valid but crash on malformed requests. Always specify error handling explicitly.

Database and Data Layer

Schema Generation

claude "Create a PostgreSQL schema for a multi-tenant SaaS app. Tables needed: organizations, users (belongs to organization), projects (belongs to organization), and tasks (belongs to project, assigned to user). Include: UUID primary keys, created_at/updated_at timestamps on all tables, proper foreign keys with ON DELETE CASCADE, a unique constraint on user email per organization, and indexes on all foreign key columns. Add 5 sample INSERT statements per table for testing."

Why this works: "Multi-tenant" tells Claude the data isolation pattern. Specifying UUID keys, timestamp columns, cascade behavior, and the unique constraint scope eliminates the most common schema review comments. The sample data request ensures the schema actually runs without errors.

Variations:

  • For MySQL: Replace "PostgreSQL" with "MySQL 8.0 using InnoDB engine"
  • For migrations: Add "Format as Prisma schema instead of raw SQL, and generate the initial migration"
  • For analytics: Add "Include an events table with a JSONB payload column, indexed with GIN, for audit logging"

Common mistakes: Saying "create a database schema for my app" without specifying relationships, key types, or constraints produces a schema that looks reasonable but needs 30 minutes of revisions. The constraint and index specifications are where the production-readiness lives.

Testing

Comprehensive Test Setup

claude "Set up Vitest with React Testing Library for this TypeScript React project. Create: a test for the Button component that checks rendering, click handling, disabled state, and loading state. An integration test for the LoginForm that mocks the auth API call, fills the form, submits, and verifies redirect on success and error message on failure. Add a test utility file with a renderWithProviders function that wraps components in the app's context providers. Add test and test:coverage scripts to package.json."

Why this works: Testing prompts fail when they're too generic ("write tests for this component"). This template names four specific test cases for the unit test and two complete user flows for the integration test. The utility file request ensures subsequent tests share a common setup, which is the part most developers skip.

Variations:

  • For Playwright E2E: Replace the test framework with "Set up Playwright for end-to-end testing. Include a test that navigates to the login page, fills credentials, submits, and verifies the dashboard loads"
  • For API testing: "Set up Supertest with Vitest for the Express API. Test the /auth/register endpoint with valid data, duplicate email, and missing required fields"

Common mistakes: Asking Claude to "write tests" without specifying the test runner, assertion style, or mocking approach produces tests that may conflict with your existing test configuration. If you already have Jest in the project, say so, or Claude might scaffold Vitest and create a configuration conflict.

Expected output: Test configuration file, 2-3 test files with passing tests, a shared test utilities file, and updated package.json scripts. Running npm test should pass immediately.

Refactoring

Component Decomposition

claude "This UserDashboard component is 400 lines long. Refactor it by: extracting the stats cards into a StatsGrid component, the activity feed into an ActivityFeed component, and the sidebar navigation into a DashboardNav component. Keep the data fetching in UserDashboard and pass data down as props. Create TypeScript interfaces for all props. Preserve all existing functionality and don't change any CSS class names."

Why this works: Refactoring prompts need constraints. "Refactor this component" without boundaries lets Claude rewrite everything, potentially changing behavior. Naming the exact components to extract, specifying where data fetching stays, and requiring preserved CSS class names means the refactored code drops in without breaking the UI or tests.

Variations:

  • For hook extraction: "Extract the data fetching logic into a useUserDashboard custom hook. Return the loading state, error state, and all data objects. Keep the component purely presentational"
  • For state management migration: "Move the local useState calls into a Zustand store. Export typed selectors for each piece of state. Keep the component renders identical"

Common mistakes: Not saying "preserve existing functionality" or "don't change CSS class names" is how refactoring prompts produce code that looks cleaner but subtly breaks three other pages. Always include preservation constraints in refactoring templates.

Debugging

Systematic Bug Investigation

claude "Users report that the checkout form submits twice on slow connections. Investigate: check the form's onSubmit handler for missing event.preventDefault() or missing disabled state during submission. Check if the submit button lacks a loading/disabled state. Check for React StrictMode double-render issues. Check if the API call has retry logic that could cause duplicates. Propose a fix and add an idempotency safeguard."

Why this works: Most debugging prompts say "fix this bug." That forces Claude to hypothesize, search, and fix in one pass, often jumping to the first plausible cause. This template lists the four most likely root causes for double-submission, directing Claude to check each one systematically. The idempotency request adds defense-in-depth.

Variations:

  • For performance issues: "The dashboard takes 8 seconds to load. Investigate: check for N+1 queries in the API, unnecessary re-renders in React components, unoptimized images, and missing database indexes. Measure the time each fix saves"
  • For auth bugs: "Users are getting logged out randomly. Check: JWT expiration handling, refresh token rotation, cookie settings (SameSite, Secure, HttpOnly), and whether concurrent requests race on token refresh"

Common mistakes: Telling Claude "fix the double submit bug" often results in adding a single guard (like disabled={loading}) without checking whether the actual cause is something deeper like retry logic or StrictMode. Listing specific investigation targets produces more thorough fixes.

Code Review and Quality

Pre-PR Review Template

claude "Review the changes in this branch for a PR. Check for: security issues (SQL injection, XSS, exposed secrets), missing error handling on async operations, TypeScript type safety (no 'any' types, proper null checks), accessibility on any new UI components (ARIA labels, keyboard navigation), and performance concerns (unnecessary re-renders, missing useMemo/useCallback). Format findings as a list with severity (critical/warning/info) and file location."

Why this works: Code review prompts that say "review this code" get surface-level feedback ("consider adding comments"). Specifying the five review dimensions and the output format means Claude produces a structured report you can act on directly. The severity levels help you prioritize.

Variations:

  • For backend focus: Replace accessibility/re-renders with "N+1 queries, missing rate limiting, and improper error propagation"
  • For security audit: "Focus exclusively on security: check all user inputs, authentication boundaries, authorization checks, sensitive data handling, and dependency vulnerabilities"

Common mistakes: Running code review without specifying what to look for produces generic suggestions like "add more comments" and "consider error handling" without identifying the actual problems in your diff.

Feature Development

End-to-End Feature Build

claude "Add a comment system to blog posts. Requirements: comments stored in a PostgreSQL comments table with id, post_id, author_name, content, created_at. API endpoints: GET /posts/:id/comments and POST /posts/:id/comments with Zod validation. React component showing threaded comments with a reply form. Optimistic UI update on new comment submission. Rate limit to 5 comments per minute per IP. Include the database migration."

Why this works: This prompt covers the full vertical slice: database, API, and frontend in one request. Specifying optimistic UI, rate limiting, and the migration file means Claude builds the feature as a complete unit rather than leaving gaps you'll discover during testing. The rate limit specification is the kind of detail that separates a prototype from production code.

Variations:

  • Add real-time: "Add WebSocket support so new comments appear for all viewers without refreshing"
  • Add moderation: "Include an isApproved boolean field and an admin endpoint to approve/reject comments"

Common mistakes: Building features in isolated layers ("create the API," then separately "create the component") loses context between prompts. Claude produces better code when it can see the full feature scope and make consistent decisions about data shapes, error handling, and naming.

Infrastructure and DevOps

CI/CD Pipeline Setup

claude "Create a GitHub Actions workflow for this TypeScript monorepo. On push to main: run TypeScript type checking, run Vitest tests, build the Next.js app, and deploy to Vercel. On pull request: run type checking and tests only, post a preview deployment link as a PR comment. Cache node_modules between runs using pnpm lockfile hash. Fail fast if any step errors."

Why this works: CI/CD prompts need branch-specific behavior defined upfront. Specifying what runs on main vs. PRs, the caching strategy, and the preview deployment behavior means the workflow works correctly on the first push without needing three rounds of "also add this" fixes.

Variations:

  • For Docker: "Build and push a Docker image to GitHub Container Registry on main, tagged with the git SHA and 'latest'"
  • For database migrations: "Add a step that runs Prisma migrations against the staging database before deployment, with a rollback step if deployment fails"

Common mistakes: Saying "set up CI/CD" without specifying the branch strategy, caching, or deployment target produces a minimal workflow that runs tests but doesn't deploy anything. The deployment and caching details are where the real value lives.

Configuration and Environment

Project Configuration Audit

claude "Audit this project's configuration. Check: tsconfig.json has strict mode enabled and proper path aliases. ESLint config catches unused imports, consistent formatting, and React hook dependency warnings. Package.json has correct scripts for dev, build, test, and lint. Environment variables are validated at startup (not just process.env access scattered through code). Flag any configuration that could cause silent failures in production."

Why this works: Configuration issues cause the most frustrating bugs because they fail silently or intermittently. This template targets the four configuration surfaces that matter most and specifically asks about production failure modes, which is the lens most configuration reviews miss.

Variations:

  • For deployment: "Also check Dockerfile for multi-stage build efficiency, .dockerignore completeness, and health check endpoint configuration"
  • For monorepo: "Check turbo.json pipeline configuration, workspace dependencies, and that shared packages export types correctly"

Usage Principles

These templates work because they follow three principles worth internalizing:

Specify the output shape, not just the goal. "Create an API" is a goal. "Create Express endpoints at these routes with Zod validation and consistent error responses" is an output shape. Claude works backward from the shape to build something that matches.

Name your constraints upfront. Every constraint you leave implicit is a coin flip. Tech stack, error handling, styling approach, browser support, database engine. If it matters, say it. If you don't specify it, Claude picks whatever seems reasonable, and "reasonable" might not match your project.

Include the non-obvious requirements. Rate limiting, idempotency, loading states, error boundaries, accessible labels. These are the requirements that separate a demo from production code, and they're the ones most prompts leave out. Adding them to your template costs a few extra words and saves hours of revision.

Beyond Templates

These templates solve common patterns, but your project has unique requirements. The key is building your own template library based on what works. When a Claude Code interaction produces great results, save the prompt. When it doesn't, figure out what specification was missing and add it.

For more on configuring Claude Code to your specific workflow, see the CLAUDE.md guide for defining persistent project context, or the configuration basics guide for initial setup. If you want a head start on prompt patterns, agent definitions, and reusable skills, the ClaudeFast Code Kit includes 18 specialized agents and domain skill packages that encode these patterns so you don't have to prompt-engineer from scratch every session.

Check the troubleshooting guide if you hit issues with any of these templates, and the FAQ for answers to common Claude Code questions.

Last updated on

On this page

Stop configuring. Start shipping.Everything you're reading about and more..
Agentic Orchestration Kit for Claude Code.