The art of prompting
with Claude Code
Master the art of communicating with AI. A good prompt makes the difference between a generic answer and a result perfectly tailored to your needs.
The 5 principles of good prompting
These principles are the foundation of every effective interaction with Claude Code. Master them and you will get 10x better results.
Be specific
Provide context and clear constraints. The more precise your prompt, the more relevant the response.
# Vague"Make me a form"# Specific"Create a contact form in React with TypeScript.Fields: name (required), email (required, valid), message (required, min 20 chars).Use react-hook-form with Zod validation.Style with Tailwind CSS, responsive mobile-first.Show a confirmation toast after submission."
Define a role
Give Claude an identity to frame its responses. The role influences the level of detail, vocabulary and approach.
"You are a senior software architect specializing in React and Next.js.You prioritize maintainability, performance and best practices.You comment your code in English and explain each architectural decision."
Specify the expected format
Clearly indicate the desired response structure: code, list, table, JSON, markdown, etc.
"Generate the response in the following format:1. A summary in 2-3 sentences2. The complete code with inline comments3. A table of required dependencies (name | version | usage)4. Step-by-step installation instructions"
Give examples (few-shot)
Show Claude what you expect with concrete examples. This is the most powerful technique for getting the exact format you want.
"Generate variable names following this pattern:Example 1: logged in user → isUserLoggedInExample 2: number of products in cart → cartItemCountExample 3: last update date → lastUpdatedAtNow generate for:- form being submitted- email validation error- filtered orders list"
Iterate and refine
Prompting is a dialogue. Progressively refine your requests based on the responses you get.
# Iteration 1"Create a Button component"# Iteration 2"Add variants: primary, secondary, ghost and danger"# Iteration 3"Add icon support on left and right,a loading state with a spinner, and the disabled prop"# Iteration 4"Add unit tests with Testing Libraryand Storybook stories for each variant"
The golden rule
Ready-to-use prompts
Copy, adapt and use these templates for your projects. Each template follows the 5 principles and has been optimized for the best results.
Web development
To create components, pages or complete web features.
You are a senior React/Next.js/TypeScript developer.Create a React component that [COMPONENT DESCRIPTION].Technical context:- Framework: Next.js 14 (App Router)- Language: TypeScript (strict mode)- Styling: Tailwind CSS- State management: [zustand / React Context / none]Functional specifications:- [Feature 1]- [Feature 2]- [Feature 3]Constraints:- Responsive mobile-first- Accessible (ARIA, focus management)- Performance optimized (memo, lazy loading if needed)- Error handling and loading statesGenerate the complete code with:1. The main component2. TypeScript types/interfaces3. A usage example4. Unit tests (Vitest + Testing Library)
How to customize
Documentation
To generate clear and structured technical documentation.
You are a senior technical writer.Write the technical documentation for [PROJECT/MODULE NAME].Target audience: [junior developers / internal team / open-source]Expected structure:1. Overview (2-3 sentences)2. Installation and prerequisites3. Configuration4. Quick Start guide5. API Reference (each function with parameters, return, example)6. Advanced usage examples7. FAQ and troubleshootingConventions:- Code examples in [TypeScript/Python/etc.]- All snippets must be copyable and functional- Use admonitions (note, warning, tip) when relevant- Include a navigable table of contents at the beginning
How to customize
Automation
To create robust automation scripts and pipelines.
You are a senior DevOps/SRE engineer.Create a script that automates [TASK DESCRIPTION].Environment:- OS: [Linux/macOS/Windows]- Language: [Bash/Python/Node.js]- Available tools: [Docker, GitHub Actions, etc.]Expected behavior:1. [Step 1 of the process]2. [Step 2 of the process]3. [Step 3 of the process]Requirements:- Robust error handling (exit codes, try/catch)- Logging with levels (info, warn, error)- Dry-run mode for testing without executing- Configurable variables via .env or CLI arguments- Idempotent (can be re-run without side effects)Generate:1. The complete commented script2. The .env.example file3. The usage README4. A cron/schedule example if relevant
How to customize
Data analysis
To explore, transform and visualize data effectively.
You are a senior data analyst expert in Python.Analyze this CSV dataset and [ANALYSIS OBJECTIVE].Data information:- Source: [source description]- Main columns: [col1, col2, col3, ...]- Volume: [approximate number of rows]- Period: [time range of data]Requested analysis:1. Exploration: descriptive statistics, missing values, distributions2. Cleaning: outlier handling, normalization, encoding3. Analysis: [correlations / trends / segmentation / prediction]4. Visualization: relevant charts with matplotlib/seabornOutput format:- Complete Python code (pandas, numpy, matplotlib)- Comments explaining each step- Interpretation of results in non-technical language- Recommendations based on insights
How to customize
Content creation
To write structured, engaging and optimized content.
You are a senior web writer specializing in [DOMAIN].Write a blog post about [TOPIC].Parameters:- Tone: [professional / casual / educational]- Length: [800-1200 words]- Target audience: [typical reader description]- Objective: [inform / persuade / tutorial]Structure:1. Catchy title (max 60 characters)2. Introduction with hook (problem/question)3. 3-5 sections with H2 subheadings4. Concrete examples and data5. Conclusion with call-to-actionSEO:- Main keyword: [keyword]- Secondary keywords: [keyword-2, keyword-3]- Meta description (max 155 characters)- Internal link suggestionsConstraints:- No unnecessary jargon- Short sentences (max 20 words)- One paragraph = one idea- Include bullet lists for readability
How to customize
Common prompting mistakes
Learn to recognize and fix ineffective prompts. Each example shows a concrete before/after.
Too vague
"Make me a website"
"Create a landing page for a project management SaaS app.Stack: Next.js 14, TypeScript, Tailwind CSS.Sections: hero with CTA, features (3 columns), pricing (3 plans), FAQ accordion.Design: modern, dark mode, subtle scroll animations."
Tip
No context
"Fix this bug"
"I have a 'TypeError: Cannot read property map of undefined' errorin my ProductList.tsx component (line 42).This component receives a 'products' prop from a REST API.The error only appears on first render, before the API responds.Here is the component: [code]"
Tip
Asking for everything at once
"Build me a complete app with auth, dashboard, API, database, tests, CI/CD and deployment"
"Let's start with the database.Create the Prisma schema for a task management app with:- Table User (id, email, name, createdAt)- Table Project (id, name, ownerId, createdAt)- Table Task (id, title, status, projectId, assigneeId, dueDate)Relations: User 1-N Project, Project 1-N Task, User 1-N Task"
Tip
Not iterating
"That's not what I wanted" (without more details)
"The component is well structured, but I'd like 3 changes:1. Replace the blue button with a teal-to-cyan gradient2. Add a fadeIn animation on component mount3. The email field should validate the format in real-time (not only on submit)"
Tip
Advanced prompting for power users
Go beyond the basics with techniques that leverage the full power of Claude Code.
Prompt chaining (multi-step sequencing)
Break down a complex task into a sequence of prompts where each step feeds the next.
# Etape 1 : Analyse"Analyse ce codebase et identifie les problemes de performance.Liste chaque probleme avec : fichier, ligne, severite, description."# Etape 2 : Priorisation (utilise la sortie de l'etape 1)"A partir de cette liste de problemes, cree un plan d'action priorise.Criteres : impact utilisateur, complexite de correction, risque de regression."# Etape 3 : Implementation (utilise la sortie de l'etape 2)"Implemente la correction du probleme #1 : [description].Genere le code corrige, les tests de non-regression, et un benchmark avant/apres."# Etape 4 : Validation"Revois les corrections appliquees. Verifie qu'elles ne cassent rienet que les tests passent. Suggere des ameliorations supplementaires si pertinent."
Why it works
Multi-agent orchestration
Use multiple specialized agents working in parallel on different aspects of a problem.
# Dans votre CLAUDE.md, definissez des agents specialises :## Agents disponibles| Agent | Role | Quand l'utiliser ||----------------|-----------------------------|-------------------------------|| planner | Planification | Avant toute feature complexe || tdd-guide | Test-Driven Development | Nouvelles features, bug fixes || code-reviewer | Revue de code | Apres chaque implementation || security-check | Analyse de securite | Avant chaque commit || architect | Decisions d'architecture | Choix techniques importants |# Exemple d'utilisation dans un prompt :"Utilise l'agent planner pour decomposer cette feature en taches.Puis lance en parallele :- Agent 1 (tdd-guide) : ecrit les tests pour le module auth- Agent 2 (tdd-guide) : ecrit les tests pour le module API- Agent 3 (security-check) : analyse les implications securiteUne fois les tests ecrits, implemente le code pour les faire passer."
Parallelism
Complex workflows with agents
Combine chaining, multi-agents and persistent context for production workflows.
# Workflow complet : nouvelle feature du planning a la production## Phase 1 : Recherche et planification"Recherche les implementations existantes de [feature] sur GitHub.Evalue les 3 meilleures options selon : securite, extensibilite, pertinence.Genere un plan d'implementation detaille avec phases et risques."## Phase 2 : TDD (Test-Driven Development)"En suivant le plan, ecris d'abord les tests (RED).Pour chaque module :1. Ecris le test → verifie qu'il echoue2. Ecris l'implementation minimale → verifie qu'il passe (GREEN)3. Refactorise → verifie que tout passe toujours (REFACTOR)"## Phase 3 : Revue et securite"Lance en parallele :- Code review : qualite, patterns, maintenabilite- Security review : injections, auth, secrets, XSS- Performance review : N+1, memory leaks, bundle sizeCorrige les issues CRITICAL et HIGH avant de continuer."## Phase 4 : Integration et deploiement"Cree la PR avec un resume complet des changements.Verifie que le CI passe. Deploie en staging pour validation."
CLAUDE.md: Your secret weapon
The CLAUDE.md file is the persistent context that Claude Code reads at every session. It is the key to getting consistent, project-tailored results.
Structure of an effective CLAUDE.md
A good CLAUDE.md turns Claude into a team member who knows your project inside out.
# CLAUDE.md## ProjetNom : MonApp, Application SaaS de gestion de projetStack : Next.js 14, TypeScript, Tailwind CSS, Prisma, PostgreSQLRepo : monorepo avec apps/ (web, api) et packages/ (ui, utils, config)## Conventions de code- Immutabilite : toujours creer de nouveaux objets, jamais muter- Fichiers < 400 lignes, fonctions < 50 lignes- Nommage : camelCase (variables), PascalCase (composants), kebab-case (fichiers)- Commentaires en francais, code en anglais- Gestion d'erreurs explicite a chaque niveau## Architecture- Feature-based : src/features/[feature]/{components,hooks,utils,types}- Repository pattern pour l'acces aux donnees- API responses : { success, data, error, meta }## Tests- Minimum 80% de couverture- TDD obligatoire : RED → GREEN → REFACTOR- Stack : Vitest + Testing Library + MSW pour les mocks API## Git- Conventional commits : feat:, fix:, refactor:, test:, docs:- PR avec description detaillee et test plan- Jamais de push force sur main## Securite- Pas de secrets en dur, utiliser .env- Validation des inputs a toutes les frontieres- Requetes parametrees (pas de concatenation SQL)## Agents| Agent | Usage ||-------|-------|| planner | Avant toute feature complexe || tdd-guide | Nouvelles features, corrections || code-reviewer | Apres chaque implementation || security-reviewer | Avant chaque commit |
Where to place the file
CLAUDE.md at the root of your project. Claude Code reads it automatically at the start of each session. You can also have CLAUDE.md files per folder for module-specific context.Warning
The 3 levels of CLAUDE.md
Global
~/.claude/CLAUDE.md
Personal preferences applied to all your projects (language, style, general conventions).
Project
./CLAUDE.md
Project-specific context: stack, architecture, team conventions, configured agents.
Module
./src/features/auth/CLAUDE.md
Ultra-specific context for a module: schema, API, particular business constraints.
Continue your learning
Prompting is a skill that improves with practice. Explore the other guides to become a Claude Code expert.