Claude Code Prompt Engineering: Complete Guide 2026
If you have been using Claude Code but getting inconsistent results, the problem is almost certainly your prompts. This guide teaches you 10 proven prompt engineering patterns — from system-level CLAUDE.md optimization to task-level chain-of-thought prompting. Learn how to structure tasks, manage context windows, coordinate multi-file changes, and avoid the 4 most common anti-patterns. Includes copy-paste templates for bug fixes, feature implementation, and code review. Your Claude Code output quality will improve dramatically starting today.
Intermediate · 30 min · Jul 19, 2026
TL;DR
If you're searching for "how to write better prompts for Claude Code," the short answer is: CLAUDE.md is your system prompt, task descriptions are your precision tool, and context management is your superpower. This guide covers 10 proven prompt engineering patterns — from system-level CLAUDE.md optimization to task-level chain-of-thought prompting — that will make Claude Code produce better code, catch more bugs, and waste fewer tokens.
Core Insight
Claude Code isn't just a code autocomplete tool — it's a conversational AI coding agent that reads your entire repository, understands project conventions, and executes multi-step coding tasks. The quality of its output is directly proportional to the quality of your prompts.
Most developers under-invest in prompt engineering for Claude Code. They throw vague instructions like "fix the bug" or "add authentication" and wonder why the output doesn't match their expectations. The difference between a 3/10 Claude Code experience and a 9/10 experience is almost entirely prompt engineering.
This guide is part of the Claude Code Hub — your central resource for mastering Claude Code as an AI builder.
1. CLAUDE.md: Your Project-Level System Prompt
CLAUDE.md is the single most impactful prompt engineering lever in Claude Code. It's a markdown file placed at your project root that gets prepended to every Claude Code session.
What Goes in CLAUDE.md
Think of CLAUDE.md as the onboarding document you wish you had when joining a new codebase. It should contain:
- Project overview: What does this project do? Who is it for?
- Tech stack: Exact versions of frameworks, libraries, and tools
- Code conventions: Naming patterns, file organization, linting rules
- Architecture decisions: Why certain patterns were chosen over alternatives
- Common commands: Build, test, lint, deploy commands
- Constraints: What NOT to do (e.g., "never modify the database schema directly")
Example CLAUDE.md
# Project: FastAPI SaaS Backend
## Stack
- Python 3.12, FastAPI 0.115, SQLAlchemy 2.0, PostgreSQL 16
- Pydantic v2 for validation, Alembic for migrations
- Pytest + pytest-asyncio for testing
## Conventions
- All routes return Pydantic models, never raw dicts
- Database queries use async SQLAlchemy sessions
- Environment variables loaded from .env via pydantic-settings
- Type hints required on all function signatures
## Architecture
- Clean Architecture: routes -> services -> repositories -> models
- Services contain business logic, never routes
- Repositories are the only layer that touches SQLAlchemy
## Commands
- Run: `uvicorn app.main:app --reload`
- Test: `pytest -xvs`
- Lint: `ruff check . && mypy app/`
- Migration: `alembic upgrade head`
## Don't
- Never use raw SQL — always go through the repository layer
- Never modify alembic migrations manually
- Never commit .env filesCLAUDE.md Best Practices
| Practice | Example |
|---|---|
| Be specific, not generic | "Use async def for all route handlers" not "write good code" |
| Include version numbers | "FastAPI 0.115" not "latest FastAPI" |
| Document DON'Ts explicitly | "Never use print() — use logger.info()" |
| Keep it under 200 lines | Too long = Claude ignores parts of it |
| Update it when conventions change | Stale CLAUDE.md is worse than no CLAUDE.md |
Pro tip: Generate your initial CLAUDE.md by running Claude Code on a fresh repo and asking: "Read my entire codebase and write a CLAUDE.md that captures all conventions and patterns you observe." Then review and refine.
2. Task Prompting Patterns
Once your CLAUDE.md is solid, the next layer is how you frame individual tasks. Here are the patterns that work:
Pattern A: Specification-First Prompting
Instead of "add user authentication," write a specification:
Task: Add JWT-based user authentication
Requirements:
1. POST /auth/register — accepts email + password, returns JWT
2. POST /auth/login — accepts email + password, returns JWT
3. GET /auth/me — protected route, returns current user
4. Use bcrypt for password hashing (cost factor 12)
5. JWT tokens expire in 24 hours
6. Add a middleware that rejects requests without valid tokens on /api/* routes
Do NOT:
- Use session-based auth
- Store plaintext passwords
- Modify existing routes
After implementation, update the API documentation in docs/api.md.This pattern gives Claude Code everything it needs: what to build, technical constraints, explicit boundaries, and follow-up actions.
Pattern B: Chain-of-Thought Requests
For complex debugging or architectural decisions, ask Claude Code to think before coding:
Before making any changes, analyze the following:
1. Read the payment processing flow in src/billing/
2. Identify why duplicate charges are occurring for subscription renewals
3. List 3-5 possible root causes, ranked by likelihood
4. For each root cause, describe the fix approach
After your analysis is complete, wait for my approval before implementing the fix.This prevents Claude Code from making hasty changes to complex systems and gives you visibility into its reasoning.
Pattern C: Example-Driven Prompting
Show Claude Code what good output looks like by providing a reference:
I need to add error handling to all service methods in src/services/.
Here's the pattern I want you to follow for every method:
EXAMPLE — the getUser method should look like this after your changes:
```python
async def get_user(user_id: str) -> UserResponse:
try:
user = await self.user_repo.find_by_id(user_id)
if not user:
raise UserNotFoundError(user_id)
return UserResponse.model_validate(user)
except UserNotFoundError:
raise # Let the exception handler deal with it
except Exception as e:
logger.error(f"Unexpected error in get_user: {e}", exc_info=True)
raise ServiceError("Failed to retrieve user") from eApply this exact pattern to all other methods in src/services/. Use the same try/except structure, the same logging format, and the same error types.
### Pattern D: Iterative Refinement Loop
The best results often come from dialogue, not one-shot prompts:
1. **Prompt 1**: "Write a data export function that converts query results to CSV."
2. Claude Code produces a basic version.
3. **Prompt 2**: "Good start. Now add: (a) streaming for large datasets, (b) a progress callback, (c) configurable column selection."
4. Claude Code refines the implementation.
5. **Prompt 3**: "One more refinement: handle edge cases — empty result sets, columns with commas, Unicode characters."
Each iteration builds on the previous, and Claude Code maintains full context of the conversation.
---
## 3. Context Window Management
Claude Code works best when it has the right context — not too little (it guesses), not too much (it gets confused).
### What Claude Code Sees by Default
When you invoke Claude Code in a project:
- **CLAUDE.md** (always included)
- **Relevant files** (auto-detected based on your prompt)
- **Git status** (knows what's changed)
- **Conversation history** (within the current session)
### Adding Specific Context
Use `/add` to explicitly include files:
/add src/models/user.py src/services/auth.py src/config/settings.py
Then issue your prompt. This is more reliable than hoping Claude Code auto-discovers the right files.
### When to Start a Fresh Session
Context windows fill up. Signs you should `/clear` or start fresh:
- Claude Code starts referencing files you discussed 10 prompts ago that are no longer relevant
- Response quality degrades (hallucinations about file contents increase)
- Token usage per response spikes inexplicably
**Rule of thumb**: Start a new session for each major feature or bug fix. Don't let one session span multiple unrelated tasks.
---
## 4. Advanced Prompting Techniques
### Multi-File Coordination
When a change spans multiple files, describe the full dependency chain:
Task: Add rate limiting to all API endpoints
Files to modify:
- src/middleware/rate_limiter.py — create a new middleware using slowapi
- src/main.py — register the middleware (before all route includes)
- src/config/settings.py — add RATE_LIMIT_REQUESTS and RATE_LIMIT_WINDOW config values
- tests/test_rate_limiter.py — add tests verifying 429 responses after limit exceeded
Dependencies: settings changes must come before middleware creation.
Naming all files explicitly prevents Claude Code from missing a critical piece.
### Test-First Prompting
Ask Claude Code to write tests before implementation:
Step 1: Write pytest tests for the following API endpoint specification:
- POST /api/products with JSON body {name, price, category}
- Should return 201 with product ID on success
- Should return 422 if name is empty
- Should return 422 if price is negative
After the tests pass review, I'll ask you to implement the endpoint. Step 2 (after review): Now implement the endpoint to make these tests pass.
This leverages Claude Code's strength at test generation and ensures the implementation is guided by a spec.
### Refactoring with Safety Nets
When refactoring large codebases:
Task: Refactor src/services/order_service.py — split the 800-line file into:
- src/services/order/create.py
- src/services/order/update.py
- src/services/order/cancel.py
Safety requirements:
- Before any changes, run the existing test suite and confirm all tests pass
- After each file split, run the tests again
- If any test fails at any point, STOP and report the failure
- Do not change any function signatures — only move code between files
- Update all imports throughout the project to point to the new locations
The "run tests before/after" pattern is critical — it catches regressions immediately.
---
## 5. Anti-Patterns to Avoid
### Anti-Pattern 1: The Kitchen Sink Prompt
❌ "Build a complete e-commerce platform with user auth, product catalog, shopping cart, checkout, payment processing, order management, email notifications, admin dashboard, analytics, and a REST API. Use React for the frontend."
This is too big. Claude Code will produce shallow, buggy code across all areas. Break it into focused, sequential tasks — one feature at a time.
### Anti-Pattern 2: Assumed Knowledge
❌ "Fix the pagination bug."
What pagination? In which file? What's the bug behavior? Always include:
- File path or component name
- Expected behavior vs. actual behavior
- Error messages or stack traces if available
### Anti-Pattern 3: Contradictory Constraints
❌ "Optimize this function for speed but don't change the algorithm and keep it under 10 lines."
These constraints conflict. Prioritize: what matters most? If speed matters, the algorithm might need to change. Be clear about trade-offs.
### Anti-Pattern 4: Premature Implementation Detail
❌ "Add user registration. Use bcrypt with cost factor 12, store in PostgreSQL using asyncpg connection pool, return JWT with RS256 algorithm, and handle the email verification via SendGrid template 47."
Unless you have specific hard constraints, let Claude Code make technology choices. It often picks better patterns than over-specified instructions. Reserve ultra-specific constraints for things that genuinely matter (security, compliance, team conventions).
---
## 6. Prompt Templates You Can Steal
### Bug Fix Template
Bug: [one-line description]
Steps to reproduce:
- [step 1]
- [step 2]
- [actual behavior]
Expected behavior: [what should happen] Actual behavior: [what actually happens]
Relevant files: [comma-separated paths] Error log (if any): [paste stack trace]
Before fixing, explain the root cause.
### Feature Implementation Template
Feature: [feature name]
Acceptance criteria:
- [criterion 1]
- [criterion 2]
- [criterion 3]
Technical constraints:
- [constraint 1]
- [constraint 2]
Files to create/modify:
- [list of files with brief description of changes for each]
After implementation, run [test command] and confirm all tests pass.
### Code Review Template
Review the following files for:
- Security vulnerabilities (injection, XSS, auth bypass)
- Performance issues (N+1 queries, blocking I/O)
- Error handling gaps (unhandled exceptions, missing retries)
- Adherence to project conventions (check CLAUDE.md)
Files: [comma-separated paths]
For each issue found, provide:
- File and line number
- Severity (critical/high/medium/low)
- Description of the problem
- Suggested fix (with code)
---
## 7. Prompt Engineering for Specific Tasks
### Database Migrations
I need to add a last_login_at column (timestamp with timezone, nullable) to the users table.
Requirements:
- Generate an Alembic migration file
- Make the column nullable with a default of NULL
- The migration must be reversible (downgrade should drop the column)
- After generating, run
alembic upgrade headand verify it succeeds - If the migration fails, revert and explain the error
### API Development
Create a new API endpoint: GET /api/users/{user_id}/orders
Query parameters:
- status (optional): filter by order status
- limit (optional, default 20, max 100): pagination limit
- offset (optional, default 0): pagination offset
Response format:
{
"items": [...],
"total": 42,
"limit": 20,
"offset": 0
}Requirements:
- Add proper input validation (Pydantic models)
- Add OpenAPI documentation
- Handle 404 if user doesn't exist
- Add appropriate logging
### Testing
Write comprehensive tests for src/services/payment_service.py
Coverage requirements:
- Happy path: successful payment processing
- Edge cases: zero amount, negative amount, max amount
- Error cases: payment gateway timeout, insufficient funds, invalid card
- Mock external dependencies (Stripe API)
- Use pytest fixtures for common setup
Test file: tests/test_payment_service.py
---
## 8. Measuring Prompt Quality
How do you know if your prompts are good? Track these metrics:
### Objective Signals
- **First-attempt success rate**: Did Claude Code nail it on the first try, or did it take 3+ revisions?
- **Token efficiency**: Good prompts produce targeted, concise code changes instead of sprawling modifications
- **Bug rate**: Code produced from good prompts has fewer bugs caught in review
### Subjective Signals
- **Surprise factor**: Are you regularly surprised by how well Claude Code understood your intent?
- **Iteration count**: Do you typically need 1-2 iterations or 5-7 iterations per task?
### Quick Self-Check
After each Claude Code session, ask yourself:
1. Did I describe WHAT to build, not HOW to build it? (unless HOW matters)
2. Did I name specific files and constraints?
3. Did I include context (CLAUDE.md, relevant files, conversation history)?
4. Did I break a big task into manageable chunks?
If you answered "no" to any of these, your prompt could be stronger.
---
## Related Resources
- [Claude Code Hub](/tutorials/claude-code-hub) — Complete Claude Code knowledge base
- [Claude Code FAQ](/tutorials/claude-code-faq-common-questions-2026) — Answers to 50+ common questions
- [Claude Code Workflow Patterns](/tutorials/claude-code-workflow-patterns-daily-ai-coding-2026) — Daily coding workflow optimization
- [Claude Code Complete Guide](/tutorials/claude-code-complete-guide-setup-pricing-workflows-2026) — Setup, pricing, and workflows
- [Claude Code vs Copilot vs Cursor](/tutorials/claude-code-vs-copilot-vs-cursor-indie-hacker-comparison-2026) — Indie hacker comparison
---
*Last updated: July 2026. Inspired by hundreds of Claude Code sessions across production codebases.*Related tutorials
AI Coding Agents Complete Guide: Setup, Security, Workflow & Case Studies
If you are researching AI coding agents and want to know which one to use, how to set it up safely, and what real developers are building with them — this hub organizes every tutorial, case study, and comparison we have published. Start with the decision guide below to find the right path for your skill level and goals.
AI Micro SaaS FAQ: 25 Common Questions Answered (2026)
Everything you need to know about building and profiting from AI Micro SaaS products. This FAQ covers idea generation, tech stack choices, pricing strategy, marketing on a $0 budget, legal considerations, and scaling from $100 to $10K MRR. Based on real case studies and data from successful solo builders using Claude Code, Cursor, and other AI coding tools.
Topic hub
AI Coding Tools Hub (2026)
From Copilot pricing changes to Claude Code + DeepSeek cost-saving setups—one place to compare tools, read explainers, and follow tutorials.
Explore AI Coding Tools Hub (2026) →Monetization angle
How can you make money from this trend?
WayToClawEarn focuses on verified earn playbooks—not just news. Start from these cases.
DeepSeek + Claude Code Micro SaaS
Run multiple small products on cheap inference
Claude Code bug bounty
Productize agent skills into security services