How to Write Effective Prompts for Claude Code
Master the art of prompting Claude Code. Learn patterns for code generation, debugging, refactoring, and automation with real examples that work.
The Art of Talking to Claude Code
Claude Code is an autonomous agent — it can read files, run commands, and make multi-file changes. But the quality of what it produces depends entirely on how you ask.
This isn't about "prompt engineering" tricks. It's about understanding how Claude Code processes your requests and structuring prompts to get reliable, production-quality results.
The Golden Rule: Context + Task + Constraints
Every effective Claude Code prompt follows this structure:
[Context] — What does Claude Code need to know about your project?
[Task] — What exactly do you want it to do?
[Contraints] — Boundaries, style guides, things to avoid?
Bad Prompt ❌
Fix the login page
This is too vague. Claude Code doesn't know what's wrong, what to fix, or what "fixed" looks like.
Good Prompt ✅
[Context] I'm working on a Next.js app with NextAuth.js authentication.
The login page is at src/app/login/page.tsx.[Task] Users are reporting that after login, they get redirected to
the homepage instead of the page they were on before login.
[Constraints]
- Preserve existing UI components
- Use the NextAuth callbackUrl pattern
- Don't change the auth provider configuration
- Test the fix by analyzing the redirect flow
10 Prompt Patterns That Work
Pattern 1: The Specification Prompt
Best for: Code generation tasks
Build a React hook called useDebounce that:
- Takes a value and delay (ms) as parameters
- Returns the debounced value
- Cleans up timers on unmount
- Is fully typed with TypeScript generics
- Includes a JSDoc comment
Claude Code generates the hook, types, and even suggests where to place it in your project.
Pattern 2: The Discovery Prompt
Best for: Understanding existing code
I need to understand how pagination works in this project.
Read the relevant files and explain:
1. Where the pagination logic lives
2. How page/size params are passed
3. What the default page size is
4. How total count is calculated
5. Where I should make changes if I want to increase max page size
Pattern 3: The Checklist Refactor
Best for: Safe refactoring
Refactor the user profile component. Follow this checklist:
- [ ] Extract API calls into a custom hook
- [ ] Move form validation to a separate utility
- [ ] Add loading states to all async operations
- [ ] Add error boundaries
- [ ] Write unit tests for the extracted hook
- [ ] Ensure all existing functionality is preservedDo ONE item at a time and verify before moving to the next.
Pattern 4: The Auto-Fix
Best for: Fixing errors and bugs
The build is failing. Here's the error message:error TS2322: Type 'string | undefined' is not assignable to type 'string'
Find the source of this error and fix it. Check:
1. All files that use this type
2. Upstream functions that return the value
3. Any missing null checks or default values
Pattern 5: The Audit
Best for: Code quality and security
Audit the API routes in src/app/api/ for security issues:
1. Check for missing authentication checks
2. Check for SQL injection vulnerabilities
3. Check for mass assignment vulnerabilities
4. Check for rate limiting
5. Check input validationReport each issue with file:line and severity.
Pattern 6: The One-Shot Boilerplate
Best for: Creating new files
Create a new API route at src/app/api/users/[id]/settings/route.ts.
It should:
- GET: Return user settings (requires auth)
- PUT: Update user settings (requires auth)
- Validate all input with Zod
- Return proper HTTP status codes
- Include error handling
- Use the existing database utility at src/lib/db.ts
Pattern 7: The Incremental Builder
Best for: Complex multi-step tasks
Step 1: Create a data model for blog posts with Prisma
Step 2: Create CRUD API routes for the model
Step 3: Create a React component to display posts
Step 4: Add the page to the navigation
Step 5: Write tests for the API routesTell me when each step is done. Don't proceed to the next
step until I confirm.
Pattern 8: The Comparison Prompt
Best for: Decision making
Help me decide between using Prisma vs Drizzle ORM for this project.Current setup:
- Next.js 14 with TypeScript
- PostgreSQL database
- Team of 3 developers
- Need migrations, type safety, and good DX
Compare:
1. Query syntax
2. Migration workflow
3. Type safety
4. Performance
5. Learning curve
6. Community ecosystem
Give me a recommendation with pros and cons.
Pattern 9: The Documentation Generator
Best for: Keeping docs in sync
Generate JSDoc comments for all exported functions in src/lib/utils.ts.
Include @param, @returns, and @example for each function.Also generate a README section that documents the utility library.
Pattern 10: The "Explain Like I'm 5"
Best for: Learning and debugging
Explain how the authentication flow works in this project.
Start from the login button click and trace through to the
final session token. I want to understand:1. What happens client-side
2. What the API endpoint does
3. How the session is created
4. Where the session is validated on subsequent requests
5. How logout works
Use simple language. Include a flow diagram structure.
Real Prompt Templates
Template: New Feature
Add [feature] to [component/file].Acceptance criteria:
- [criterion 1]
- [criterion 2]
- [criterion 3]
Files this affects:
- [file 1]
- [file 2]
Quality checks:
- Run the existing tests
- Don't break existing functionality
- Use existing patterns/styles
Template: Bug Fix
Bug: [description of the bug]
Location: [where it likely lives]
Reproduction: [steps to reproduce]Expected behavior: [what should happen]
Actual behavior: [what actually happens]
Investigation:
1. Find the root cause
2. Trace through the code path
3. Check for similar patterns
Fix:
1. Apply the fix
2. Verify existing tests pass
3. Add a test for the specific bug case
Template: Code Review
Review all uncommitted changes in the current branch.
Check for:
- TypeScript strict mode violations
- Missing error handling
- Performance issues (unnecessary rerenders, large bundles)
- Security concerns (XSS, CSRF, injection)
- Test coverage gaps
- Hardcoded values that should be configFormat results by severity: Critical / Warning / Suggestion.
Tips for Better Results
1. Be Specific About Scope
❌ "Check the codebase for issues"
✅ "Check src/app/api/ for missing authentication checks"
2. Use Project-Specific Terms
❌ "Fix the database request"
✅ "Optimize the Prisma query in getUserByEmail to use select instead of include"
3. Provide Examples When Possible
Use the same pattern as the existing
createUser function in src/lib/user.ts.
4. Request Verification
After making changes, run npm run test
and report the results.
5. Use Explicit Constraints
Do NOT modify:
- Any files in src/auth/
- The database schema
- Environment variablesDo NOT change the public API surface.
Common Mistakes
Mistake 1: Overloading
❌ "Rewrite the entire app in a different framework"
(Split into phases instead)
Mistake 2: Ambiguity
❌ "Make it look better"
✅ "Use the shadcn/ui card component with the muted foreground color"
Mistake 3: Missing Context
❌ "Fix this type error" (without showing the error)
✅ Include the actual error message and file location
Mistake 4: No Verification Step
❌ "Write tests"
✅ "Write tests, run them, report coverage, and fix any failures"
Quick Reference Card
| Goal | Prompt Style | |------|-------------| | Generate code | Specification pattern | | Understand code | Discovery pattern | | Refactor | Checklist pattern | | Fix errors | Auto-fix pattern | | Audit quality | Audit pattern | | Create boilerplate | One-shot pattern | | Build complex features | Incremental pattern | | Make decisions | Comparison pattern | | Write docs | Documentation pattern | | Learn codebase | Explain pattern |
---
Master these patterns and Claude Code becomes 10x more productive. Start with the Specification and Discovery patterns — they cover 80% of daily use cases.
New to Claude Code? Install it in 5 minutes. Already using it? See how Claude Code compares to Cursor.
Related Articles
How to Set Up Claude Code with DeepSeek API (Save 97% on AI Coding Costs)
Step-by-step guide to using Claude Code with DeepSeek as the backend model instead of Anthropic. Cut your AI coding costs by 97% while keeping the same workflow and tools.
How to Build a Full-Stack App with Claude Code: From Zero to Deploy
Step-by-step tutorial on building a complete full-stack application using Claude Code as your AI pair programmer — from project setup through database, API, frontend, and deployment.
The Truth About AI Coding in 2026: What Works, What Doesn't, and How to Get Real Results
An honest look at AI-assisted coding in 2026 — where AI coding agents excel, where they fail, the '70% problem,' and a practical framework for getting real productivity gains without the hype.