20 Best Claude Prompts for Coding: Copy-Paste Developer Cookbook
20 copy-paste ready Claude prompts for coding. Battle-tested prompts for writing code, debugging, refactoring, reviews, docs, and architecture decisions.
20 Best Claude Prompts for Coding: Copy-Paste Developer Cookbook
The difference between a mediocre Claude response and production-ready code comes down to prompt structure. This cookbook contains 20 battle-tested prompts organized by developer workflow. Every prompt is copy-paste ready -- replace the [bracketed placeholders] with your specifics and send. Works with Claude Opus 4.6, Claude Sonnet 4.5, and Claude Code.
Section 1: Code Writing Prompts
Prompt 1: Write a Function with Full Specification
When to use it: You need a utility or business logic function with proper edge cases, types, and error handling.
Write a [language] function that [describe what it does].
Requirements:
- Input: [describe parameters and their types]
- Output: [describe return value and type]
- Edge cases to handle: [list 2-3 edge cases]
- Error handling: [throw errors / return null / return Result type]
Context: This function will be used in [describe where it fits — API handler, React component, CLI tool, etc.].
Constraints:
- No external dependencies unless absolutely necessary
- Follow [style guide or conventions, e.g., "Google TypeScript style"]
- Include JSDoc / docstring comments
Write the function, then write 3 unit tests covering normal input, edge case, and error case.
Example output (abbreviated):
For a "validate email" request, Claude returns a typed function with JSDoc, input sanitization, RFC-based regex, and three grouped tests (happy path, empty string, max length exceeded). The "Context" line is key -- telling Claude where the function lives changes error handling patterns significantly.
Prompt 2: Create a REST API Endpoint
When to use it: You need a complete API endpoint with validation, error handling, and proper HTTP status codes.
Create a [framework] API endpoint for [describe the operation].
Endpoint: [HTTP method] [path]
Authentication: [required/optional/none]
Request body/params:
[list fields with types and validation rules]
Business logic:
1. [Step 1]
2. [Step 2]
3. [Step 3]
Response format:
- Success (200): { [describe shape] }
- Validation error (400): { error: string, fields: string[] }
- Not found (404): { error: string }
- Server error (500): { error: string }
Tech stack context:
- ORM: [Prisma / Drizzle / Sequelize / raw SQL]
- Validation: [Zod / Joi / manual]
- Database: [PostgreSQL / MongoDB / etc.]
Include input validation, proper error handling, and TypeScript types for request and response.
Example output (abbreviated):
Claude returns a complete route handler with Zod schema, try/catch blocks with specific error codes, Prisma calls, and TypeScript response typing -- typically 60-80 lines of drop-in code.
Prompt 3: Build a React Component
When to use it: You need a complete React component with state, event handlers, accessibility, and styling.
Build a React component: [ComponentName]
Purpose: [what the component does and where it appears in the app]
Props:
- [propName]: [type] - [description]
- [propName]: [type] - [description]
Behavior:
- [Describe interaction 1]
- [Describe interaction 2]
- [Describe loading/error/empty states]
Styling: [Tailwind CSS / CSS Modules / styled-components]
State management: [useState / useReducer / Zustand / none]
Requirements:
- Fully typed with TypeScript
- Accessible (proper ARIA attributes, keyboard navigation)
- Responsive (mobile-first)
- Include a Props interface exported separately
Do NOT use any UI library components. Build from primitives (div, button, input, etc.) with [Tailwind/CSS].
Example output (abbreviated):
Claude returns a complete component file with exported Props interface, hooks, event handlers, conditional rendering for loading/error/empty states, Tailwind classes, and a usage example with sample props.
Prompt 4: Write Comprehensive Tests
When to use it: You have existing code that lacks tests and want a thorough suite beyond the basics.
Write tests for the following code:
```[language]
[paste your code here]
Testing framework: [Jest / Vitest / Pytest / Go testing] Testing style: [describe — e.g., "arrange-act-assert", "given-when-then"]
Cover these scenarios:
- Happy path with typical input
- Edge cases: [list specific ones, e.g., "empty array", "null input", "max integer"]
- Error handling: verify correct errors are thrown/returned
- Boundary conditions: [e.g., "exactly at character limit", "zero items"]
Mocking requirements:
- Mock [external service/database/API] using [jest.mock / vi.mock / unittest.mock]
- Do NOT mock [specify what should use real implementations]
Generate at least [number] test cases. Group them with describe/context blocks by behavior category.
**Example output (abbreviated):**
Claude produces a test file with grouped `describe` blocks ("successful payments", "validation failures", "external API errors", "edge cases"), each containing 3-5 focused test cases with proper mocking and assertions.
---
## Section 2: Code Review Prompts
### Prompt 5: Full Pull Request Review
**When to use it:** You want a thorough, structured review of a diff before merging.
Review this code change as a senior developer. Be direct and specific.
Review for:
- Correctness: Logic errors, off-by-one errors, race conditions
- Security: Injection vulnerabilities, auth issues, data exposure
- Performance: N+1 queries, unnecessary re-renders, memory leaks
- Maintainability: Naming, complexity, single responsibility
- Missing pieces: Error handling gaps, missing edge cases, absent tests
Format your review as:
- CRITICAL: Must fix before merge
- WARNING: Should fix, acceptable to defer
- SUGGESTION: Nice to have improvements
- GOOD: Things done well (include at least one)
**Example output (abbreviated):**
Claude returns a prioritized review: "CRITICAL: The `deleteUser` handler has no authorization check -- any logged-in user can delete any account. WARNING: N+1 query on line 23 runs inside a loop. SUGGESTION: Rename variable `d` to `deletedAt`. GOOD: Error handling in payment flow is thorough with specific error types."
---
### Prompt 6: Find Bugs in Code
**When to use it:** You suspect bugs but cannot pinpoint them. This prompt makes Claude actively hunt for problems.
Find bugs in this code. Be thorough — check for both obvious and subtle issues.
[paste your code here]
This code is supposed to: [describe expected behavior]
Check specifically for:
- Logic errors that produce wrong results
- Null/undefined access that would crash at runtime
- Race conditions or async issues
- Off-by-one errors in loops or slicing
- Resource leaks (unclosed connections, listeners, file handles)
- Type coercion issues (especially in JavaScript/TypeScript)
For each bug found, provide:
- The exact line or section
- What goes wrong and under what input
- The fix (show corrected code)
**Example output (abbreviated):**
Claude identifies specific bugs with concrete inputs that trigger them. For example: "Line 12: `array.length - 1` should be `array.length` in the for loop boundary. When the array has 5 elements, the last element is never processed. Input `[1,2,3,4,5]` returns `[1,2,3,4]` instead of the expected `[1,2,3,4,5]`." followed by the corrected code.
---
### Prompt 7: Suggest Code Improvements
**When to use it:** Your code works but needs cleanup. You want incremental improvements, not a full rewrite.
Suggest improvements for this working code. It functions correctly but needs improvement.
[paste your code here]
Focus areas (rank by priority):
- Readability and clarity
- Performance
- Error resilience
- Idiomatic [language] patterns
Rules:
- Do NOT change the public interface (function signatures, exported types)
- Keep changes minimal and incremental — I want to understand each improvement
- For each suggestion, explain WHY it is better, not just what to change
Format: List each improvement separately with before/after code snippets.
**Example output (abbreviated):**
Claude returns 4-6 specific improvements, each with a rationale. For example: "Replace the nested if-else chain (lines 15-34) with an early return pattern. This reduces nesting from 4 levels to 1 and makes the happy path obvious." followed by before and after code showing the refactored version.
---
## Section 3: Debugging Prompts
### Prompt 8: Fix an Error Message
**When to use it:** You have a specific error (stack trace, compilation error, runtime exception) and want Claude to explain it and fix it.
I'm getting this error and need help fixing it.
Error message:
[paste full error message and stack trace]
Code that triggers the error:
[paste the relevant code]
Environment:
- [Language] version: [version]
- OS: [operating system]
- Relevant packages: [list with versions]
What I've already tried:
- [attempted fix 1]
- [attempted fix 2]
Explain what causes this error, then provide the fix. If there are multiple possible causes, list them in order of likelihood.
**Example output (abbreviated):**
Claude explains the cause: "This `TypeError: Cannot read properties of undefined (reading 'map')` occurs because `response.data.items` is undefined when the API returns an empty result set." Then provides the exact fix with optional chaining or a default value.
---
### Prompt 9: Trace a Logic Bug
**When to use it:** Your code runs without errors but produces wrong output. This prompt makes Claude trace execution step by step.
My code runs without errors but produces wrong output.
Code:
[paste the full relevant code]
Expected behavior: [describe what should happen] Actual behavior: [describe what actually happens]
Example input that demonstrates the bug: [provide specific input values]
Expected output for that input: [value] Actual output for that input: [value]
Trace through the code execution step by step with my example input. Identify where the actual behavior diverges from expected behavior. Then provide the fix.
**Example output (abbreviated):**
Claude traces execution step by step: "After line 8, `total = 150`. After line 9, `discount = 0.1` -- wrong, should be 0.15 for orders over 100. Bug is on line 9: `total > 200` should be `total > 100`."
---
### Prompt 10: Diagnose a Performance Problem
**When to use it:** Your code is correct but too slow or uses too much memory.
This code is too slow and I need to optimize it.
[paste the code]
Performance context:
- Current execution time: [how long it takes]
- Acceptable execution time: [target]
- Input size: [e.g., "~50,000 records", "10MB JSON file"]
- Where it runs: [server / browser / lambda / etc.]
Profiling data (if available): [paste any profiling output, or say "none"]
Identify the performance bottleneck(s) and provide optimized code. For each optimization, explain the algorithmic complexity change (e.g., O(n^2) to O(n log n)) or the practical improvement.
**Example output (abbreviated):**
Claude identifies the bottleneck: "The nested `find()` inside `forEach` on line 14 is O(n*m) -- 2.5 billion comparisons for 50K records. Fix: Build a Map from orders indexed by userId (O(m)), then O(1) lookups. Total becomes O(n+m)." Followed by optimized code.
---
## Section 4: Refactoring Prompts
### Prompt 11: Clean Up Messy Code
**When to use it:** You have messy code that needs cleanup while preserving exact behavior.
Refactor this code to be clean and maintainable. Do NOT change its behavior.
[paste the messy code]
This code does: [brief description of what the code accomplishes]
Apply these refactoring principles:
- Extract repeated logic into helper functions
- Replace magic numbers/strings with named constants
- Simplify deeply nested conditionals
- Improve variable and function names to be self-documenting
- Remove dead code
Constraints:
- Keep the same public API / exports
- No new dependencies
- Preserve all existing behavior including edge cases
Show the refactored version, then list every change you made and why.
**Example output (abbreviated):**
Claude returns refactored code with a change log: "1. Extracted duplicated price calculation into `calculateDiscountedPrice()`. 2. Replaced magic number `86400` with `SECONDS_PER_DAY`. 3. Converted nested if/else to early-return pattern, reducing nesting from 5 levels to 2."
---
### Prompt 12: Simplify Complex Logic
**When to use it:** You have a function with too many branches and high cyclomatic complexity. You want it simplified while preserving behavior.
Simplify this function. It has too many branches and is hard to follow.
[paste the complex function]
Requirements:
- Reduce cyclomatic complexity (currently [estimated number] branches)
- Make the logic readable without comments explaining what each branch does
- Consider: lookup tables, early returns, strategy pattern, polymorphism — whatever fits best
- The function signature must stay the same
- All current behavior must be preserved
Show me the simplified version and explain your approach.
**Example output (abbreviated):**
Claude typically replaces a long if/else or switch chain with a lookup object or Map, reducing 30 lines to 10. The explanation reads something like: "Replaced the 12-branch switch statement with a `handlers` Map. Each case is now a one-line entry in the Map. The function body is reduced to a Map lookup and a fallback for unknown types. Cyclomatic complexity dropped from 14 to 3."
---
### Prompt 13: Modernize Legacy Code
**When to use it:** You are migrating old patterns to modern ones (class to hooks, callbacks to async/await, CommonJS to ESM).
Modernize this code from [old pattern] to [new pattern].
[paste the old code]
Migration targets:
- [Old thing] → [New thing] (e.g., "class components → functional components with hooks")
- [Old thing] → [New thing] (e.g., "callbacks → async/await")
- [Old thing] → [New thing] (e.g., "moment.js → date-fns")
Rules:
- Preserve all existing behavior and edge case handling
- Keep the same exports and public interface
- Add TypeScript types if converting from JavaScript
- Flag anything that cannot be directly migrated and explain why
Provide the modernized code and a migration summary listing each change.
**Example output (abbreviated):**
Claude returns modernized code with a migration summary. For class-to-hooks: converts `componentDidMount` to `useEffect`, `this.state` to `useState`, and flags edge cases: "`componentWillReceiveProps` has no direct hooks equivalent -- replaced with `useEffect` depending on `[props.userId]`."
---
## Section 5: Documentation Prompts
### Prompt 14: Add Inline Documentation
**When to use it:** You need comments, JSDoc, or docstrings added to existing code without modifying logic.
Add documentation to this code. Do NOT modify any logic — only add comments and docstrings.
[paste the code]
Documentation style: [JSDoc / Python docstrings / Go doc comments / Rust doc comments]
Add:
- Module-level comment explaining purpose and usage
- Function/method docstrings with:
- Brief description
- @param descriptions with types
- @returns description
- @throws / @raises for error conditions
- @example with a usage example
- Inline comments ONLY where the logic is non-obvious (do not comment obvious code like
i++)
Return the fully documented code.
**Example output (abbreviated):**
Claude adds documentation proportional to complexity -- simple getters get one-line descriptions, complex algorithms get detailed explanations. Inline comments explain *why*, not *what*: `// Partition step: elements less than pivot go left` rather than `// loop through array`.
---
### Prompt 15: Write a README
**When to use it:** You need a README that actually helps someone get started, not a placeholder template.
Write a README.md for this project.
README sections to include:
- Project title and one-line description
- Features (bullet list, 4-6 items)
- Quick start (install + minimal working example)
- API reference (document main exported functions/classes)
- Configuration options (if any)
- Contributing guidelines (brief)
- License
Style: Concise and practical. No filler text. Assume the reader is an experienced developer.
**Example output (abbreviated):**
Claude produces a structured README with Quick Start (5-10 lines to get running), API reference with signatures, and a configuration table. Typically 150-250 lines -- useful but readable.
---
### Prompt 16: Explain a Codebase to a New Developer
**When to use it:** A new team member needs to understand an existing codebase quickly.
Explain this codebase to a developer who is joining the team.
Write an explanation covering:
- What the project does (2-3 sentences, non-technical summary)
- Architecture overview (how the pieces fit together)
- Request flow (trace a typical user action from frontend to database and back)
- Key abstractions (important classes, interfaces, or patterns to understand)
- Where to find things (map common tasks to file locations)
- Gotchas (non-obvious things that trip up new developers)
Write for a mid-level developer. Skip the basics, explain the project-specific stuff.
**Example output (abbreviated):**
Claude produces a walkthrough tracing a real request: "POST /api/orders enters through `routes/orders.ts`, gets validated by `OrderSchema`, then calls `OrderService.create()` which handles inventory and payment in a transaction." The "Gotchas" section flags things like soft deletes: "Always filter with `where: { deletedAt: null }`."
---
## Section 6: Architecture Prompts
### Prompt 17: Design a System
**When to use it:** You are starting a new feature or service and need to think through the design before writing code.
Help me design [describe the system or feature].
Requirements:
- [Functional requirement 1]
- [Functional requirement 2]
- [Functional requirement 3]
Non-functional requirements:
- Expected load: [e.g., "10,000 requests/minute"]
- Latency target: [e.g., "p99 < 200ms"]
- Data volume: [e.g., "~5TB, growing 100GB/month"]
- Availability target: [e.g., "99.9%"]
Current tech stack: [list what you already use]
Constraints:
- [e.g., "Must integrate with existing PostgreSQL database"]
- [e.g., "Team of 3, so minimize operational complexity"]
- [e.g., "Budget: $500/month infrastructure"]
Provide:
- High-level architecture (components and how they interact)
- Data model (key entities and relationships)
- API design (main endpoints)
- Technology recommendations with justifications
- Trade-offs of this approach (what you're giving up)
- What could go wrong (failure modes and mitigations)
**Example output (abbreviated):**
Claude returns a structured design document with component descriptions, data flow, API endpoints, and a trade-offs section: "This design uses a message queue for payment processing, meaning orders are eventually consistent. The alternative (synchronous processing) is simpler but creates a single point of failure."
---
### Prompt 18: Evaluate Technology Choices
**When to use it:** You need to choose between technologies and want a structured comparison, not blog opinions.
Help me choose between [Option A] and [Option B] (and [Option C] if applicable) for [describe the use case].
My situation:
- Project type: [describe the project]
- Team expertise: [what the team knows well]
- Timeline: [how soon you need to ship]
- Scale: [expected usage / data volume]
- Existing stack: [what you already use]
Compare on these dimensions:
- Fit for my use case (does it solve my specific problem well?)
- Learning curve for my team
- Performance characteristics relevant to my use case
- Ecosystem and community (libraries, documentation, hiring)
- Operational complexity (deployment, monitoring, maintenance)
- Lock-in risk and migration path
Give me a clear recommendation with reasoning, not a "both are good, it depends" answer. Be opinionated.
**Example output (abbreviated):**
Claude provides a comparison table and a direct recommendation: "Use PostgreSQL, not MongoDB. Your data is relational, your team knows SQL, and you need transactions. MongoDB would require manual consistency handling that PostgreSQL gives you for free."
---
## Section 7: Learning Prompts
### Prompt 19: Explain a Concept with My Code
**When to use it:** You want a concept explained using your actual code, not abstract textbook examples.
Explain [concept] to me using my code as the example.
My code:
[paste your code]
I understand: [what you already know, e.g., "basic JavaScript, functions, objects"]
I'm confused about: [specific confusion, e.g., "why does this change inside the callback?"]
Explain by:
- Identifying where [concept] appears in my code
- Explaining what is happening in plain language (no jargon without definition)
- Showing what would happen if I did it wrong (contrast with a broken version)
- Giving me one small exercise to verify I understand
**Example output (abbreviated):**
Claude points to your actual code: "On line 7, `createCounter()` returns a function that references `count` from the outer scope -- this is a closure." It then shows a broken version without the closure and an exercise: "Predict what `counter()` returns after calling it three times."
---
### Prompt 20: Teach Me a Design Pattern
**When to use it:** You want to learn a design pattern with a practical example in your language, not a Java textbook from 2003.
Teach me the [pattern name] pattern.
My context:
- Language: [language]
- Framework: [framework]
- Current problem: [describe a problem you're facing that this pattern might solve]
Explain:
- What problem does this pattern solve? (in 2-3 sentences)
- Show a simple implementation in [language] (under 50 lines)
- Show how it applies to my specific problem
- When should I NOT use this pattern? (common misuse cases)
- What is the modern version of this pattern in [language/framework]? (patterns evolve — show me the 2026 way, not the Gang of Four way)
**Example output (abbreviated):**
For the Repository pattern in TypeScript, Claude explains the problem it solves, shows a 40-line implementation, applies it to your specific code, and notes the modern take: "In TypeScript with Prisma, the ORM already acts as a repository. You only need an explicit layer when you have complex query logic to unit test independently."
---
## Pro Tips: Getting More from Claude
### Use XML Tags for Structure (39% Better Results)
Anthropic's own research shows that prompts with XML-structured context produce up to 39% better results compared to unstructured prompts. Instead of pasting code after a sentence, wrap it:
Claude parses XML-like tags as semantic boundaries, treating content inside <existing_code> differently from <requirements>, producing more targeted responses.
Use CLAUDE.md for Project Context
If you use Claude Code (Anthropic's CLI), create a CLAUDE.md file in your project root. Claude reads it automatically as persistent context, so you never need to repeat "I'm using Next.js 15 with TypeScript and Tailwind" in every message.
A good CLAUDE.md includes:
- Tech stack and versions
- Code conventions (naming, file structure, patterns)
- Common commands (dev server, tests, deploy)
- Known gotchas or workarounds
Enable Extended Thinking for Complex Tasks
For architecture decisions, complex debugging, and multi-file refactoring, enable Claude's extended thinking mode (available in the API and Claude Code). This makes Claude reason step by step before generating output -- dramatically better for debugging logic errors, weighing architecture trade-offs, and behavior-preserving refactors.
Iterate, Don't Re-prompt
When Claude's response is close but not right, reply with specific feedback: "Change the error handling to return a Result type instead of throwing." Claude maintains conversation context, so iterative refinement is faster than rewriting the entire prompt.
Provide Real Examples Over Abstract Descriptions
The single biggest prompt improvement is replacing abstract descriptions with concrete examples. Instead of "handle edge cases", show an edge case input and expected output. Instead of "follow our coding style", paste 10 lines of existing code. Claude learns from examples faster than descriptions.
Conclusion
These 20 prompts cover the core developer workflow: writing, reviewing, debugging, refactoring, documenting, designing, and learning. The common thread is structure and specificity. The more precisely you frame the problem, the less time you spend correcting the output. Start with these templates, adapt them to your workflow, and save your best-performing variations.
Sources:
- Anthropic, "Claude Prompt Engineering Documentation" (2025)
- Anthropic, "Anthropic Cookbook: Structured Prompting" (2025)
- Cursor, "AI-Assisted Development Best Practices" (2025)
- SWE-bench, "Verified Benchmark Results" (November 2025)
Related Articles
AI API Pricing 2026: Cost Strategies for LLM Economics
Compare AI API pricing across providers, analyze cost optimization strategies, and explore LLM economics trends for 2026.
LLM API Economics 2026: Smart Cost Optimization Strategies
Compare AI API pricing across Claude, GPT, Gemini and learn cost optimization strategies. When to use each tier and market trends for 2026.
AI Safety 2026: Constitutional Alignment Breakthroughs
Explore 2026 advances in AI safety from Anthropic, OpenAI, and DeepMind. Constitutional AI, RLHF improvements, and alignment techniques shaping responsible AI.