Skip to main content
Prompting

Prompting basics

Learn the fundamentals of prompting with Claude Code: structure, clarity, context, and how to get the results you want from AI.

How Claude interprets your messages

When you write a prompt to Claude Code, it does more than just read your words. It analyzes the context, the structure, and the intent behind your message. Understanding this process is the key to getting accurate results on the first try.

The creative brief analogy

Picture yourself briefing a talented freelancer who knows nothing about your project. The clearer and more structured your brief is, the closer the deliverable will match your expectations. A vague brief produces a vague result. A precise brief produces a precise result. Prompting is exactly that: the art of writing the perfect brief.

Claude Code takes several layers of information into account when interpreting your request:

  1. Project context: the CLAUDE.md file, open files, the codebase
  2. Conversation history: previous exchanges in the session
  3. Your current prompt: the message you just wrote
  4. System instructions: loaded Skills and directives

The more explicit context you include in your prompt, the less Claude has to guess, and the fewer mistakes it makes.

Structure of a good prompt

An effective prompt follows a 4-part structure. You don't need to use all of them every time, but knowing them lets you activate them when the situation calls for it.

The context

Describe the situation: which project, which technology, which problem. Claude needs to understand where it's stepping in.

I'm working on a REST API in Node.js/Express with TypeScript.
The database is PostgreSQL via Prisma.
The authentication module uses JWT with refresh tokens.

The task

Describe precisely what you expect. Use action verbs: "create", "fix", "analyze", "refactor", "explain".

Create an Express middleware that verifies the JWT in the Authorization header,
extracts the user and attaches it to req.user.

The constraints

Specify the rules, limits, and non-functional requirements. This is what turns a generic answer into a solution tailored to your project.

Constraints:
- Error handling: return 401 if token is missing, 403 if token is invalid/expired
- Strict TypeScript (no any)
- The middleware must be unit-testable (JWT service injection)
- Log invalid access attempts with timestamp and IP

The output format

Tell Claude how to structure its response. Code only? With explanations? Across multiple files?

Generate:
1. The middleware in src/middlewares/auth.middleware.ts
2. The types in src/types/auth.types.ts
3. The unit tests in src/middlewares/__tests__/auth.middleware.test.ts
4. A usage example in a protected route

The 5 key prompting principles

These principles are the foundation of every effective interaction with Claude Code. Master them and you'll see dramatically better results.

Principle 1: Be specific

Specificity is the number one factor in response quality. Every detail you add eliminates an ambiguity.

# Vague (bad)
"Make me a form"
# Specific (good)
"Create a registration form in React with TypeScript.
Fields: email (required, format validated), password (required, min 8 characters,
1 uppercase, 1 digit), password confirmation.
Use react-hook-form with Zod validation.
Style with Tailwind CSS, responsive mobile-first.
Display inline errors under each field."

Principle 2: Provide context

Claude can't see your screen and doesn't know your history. Share the relevant context: the stack, the architecture, the conventions, the problem you're facing.

# No context (bad)
"Fix this bug"
# With context (good)
"I'm getting a TypeError: Cannot read property 'map' of undefined
in my ProductList.tsx component at line 42.
This component receives a 'products' prop from a REST API via useSWR.
The error occurs on the first render, before the API responds.
The component has no loading state handling."

Principle 3: Specify the format

Clearly indicate the structure of the desired response. This avoids back-and-forth and saves you time.

"Generate the response in the following format:
1. A 2-3 sentence summary
2. The complete code with inline comments
3. A table of required dependencies (name | version | usage)
4. Step-by-step installation instructions"

Principle 4: Iterate progressively

Don't ask for everything at once. Build your solution step by step, verifying each step before moving to the next.

# Iteration 1
"Create a Button component with these props: label, onClick, disabled"
# Iteration 2
"Add color variants: primary, secondary, danger, ghost"
# Iteration 3
"Add icon support (left and right) and a loading state"
# Iteration 4
"Write unit tests with Testing Library"

Principle 5: Verify the results

Ask Claude to check its own work, explain its choices, or flag potential risks.

"After generating the code, verify:
- That it compiles without TypeScript errors
- That all edge cases are handled (null, undefined, empty array)
- That there are no obvious security vulnerabilities
- That performance is acceptable for a list of 10,000 items"

Before/after examples: from beginner to optimized

Here are concrete transformations that show how a mediocre prompt becomes an excellent one.

Example 1: Creating a component

Before (beginner prompt):

"Make me a navigation component"

After (optimized prompt):

"Create a responsive Navbar component in React/TypeScript with Tailwind CSS.
- Desktop: logo on the left, nav links in the center, CTA button on the right
- Mobile: burger menu with animated sidebar (framer-motion)
- Dark mode toggle with next-themes
- Active link highlighted based on pathname (usePathname from Next.js)
- Accessible: aria-labels, visible focus, keyboard navigation
- Links: Home, Features, Pricing, Blog, Contact"

Example 2: Debugging an error

Before (beginner prompt):

"It doesn't work, help me"

After (optimized prompt):

"My login form isn't submitting data.
Expected behavior: clicking 'Sign In' sends data to POST /api/auth/login.
Observed behavior: nothing happens, no network request in the Network tab.
Stack: React 18, react-hook-form, axios.
What I've checked: handleSubmit is properly attached to the form, no console errors.
Here's the LoginForm.tsx component: [code]"

Examples by profile: developer, entrepreneur, student, creative

Effective prompting adapts to your context. Here are concrete examples by task type and profile.

Developer profile

Code refactoring

Vague prompt:

"Improve this code"

Optimized prompt:

"Refactor this calculateDiscount() function in src/pricing/discount.service.ts.
Current problems:
- Too long (120 lines), hard to test
- 4 levels of nested if/else
- Calculation logic mixed with validation logic
Refactoring criteria:
- Extract validation rules into a validateDiscountInput() function
- Extract calculation by discount type into separate functions
- Use early returns to reduce nesting
- Strict TypeScript, no any
- Preserve exactly the same behavior (tests must pass)"

Debugging a performance issue

Vague prompt:

"My app is slow"

Optimized prompt:

"Our ProductList page is slow on first load (4-6 seconds).
Observations:
- Request waterfall in the Network tab: 3 sequential API calls
- 847ms of JavaScript to parse at startup (bundle.js 2.3MB unminified)
- No lazy loading on product images
Stack: Next.js 14 App Router, React Query, 200 products loaded initially.
Analyze the 3 identified issues and propose concrete fixes
with the code for each fix. Prioritize by impact."

Writing TDD tests

Vague prompt:

"Write tests for this service"

Optimized prompt:

"Write unit tests for UserService using a TDD approach (Vitest + mocks).
Methods to test:
1. createUser(data: CreateUserDto): success, duplicate email, validation fails
2. findById(id: string): found, not found, invalid id
3. updatePassword(id, oldPwd, newPwd): success, wrong old password, new password too short
For each test:
- Arrange: set up necessary mocks
- Act: call the method
- Assert: verify the result AND side effects (logs, emitted events)
Mock the complete UserRepository. Strict TypeScript."

Entrepreneur / manager profile

Writing a sales email

Vague prompt:

"Write an email to sell my product"

Optimized prompt:

"Write a B2B prospecting email for [First Name] [Last Name], HR Director at [Company, 500 employees].
My product: HR onboarding platform that reduces new employee
integration time from 3 weeks to 5 days.
Problem it likely solves: high turnover in the first 6 months,
time-consuming manual onboarding for HR teams.
The email must:
- Start with a hook showing I've researched their company
- Present a concrete benefit (not a feature) in one sentence
- Include social proof (similar client)
- End with a clear value proposition and a simple CTA
Tone: direct and respectful of their time, no sales jargon.
Length: 150 words maximum."

Preparing a strategic report

Vague prompt:

"Help me with my report"

Optimized prompt:

"I'm preparing a report for the executive committee meeting on Tuesday about our Q1 2026 results.
Available data:
- Q1 Revenue: 842K EUR (target: 800K EUR, +5.25%)
- New clients: 23 (target: 20)
- Churn rate: 3.2% (target: < 3%, slightly above)
- NPS: 67 (stable vs Q4 2025)
Constraint: the committee expects recommendations for Q2, not just observations.
Generate the report structure with:
1. An executive summary in 5 bullets (positives and areas of concern)
2. An analysis of the revenue overperformance
3. An action plan for churn (2-3 concrete actions)
4. The 3 priority metrics to watch in Q2"

Student profile

Understanding a complex concept

Vague prompt:

"Explain neural networks to me"

Optimized prompt:

"Explain convolutional neural networks (CNNs) for computer vision.
My level: I have basics in Python and linear algebra, but no experience
in deep learning. I've taken an introductory course on classical neural networks.
What I want to understand:
1. Why CNNs are better than classical networks for images
2. What a convolution is (visual intuition, not just the formula)
3. How filters 'learn' to detect features (edges, shapes, faces)
4. Typical architecture: convolution -> pooling -> fully connected -> softmax
Use concrete analogies. Avoid jargon without explaining it.
If possible, show how it's implemented in 10 lines of PyTorch."

Summarizing and synthesizing a course

Vague prompt:

"Summarize this course"

Optimized prompt:

"Create a study sheet for the macroeconomics exam on March 20.
Chapters to cover: [paste the table of contents or key points]
Desired format:
1. Key definitions (term: definition in 1-2 sentences)
2. Important diagrams to memorize (text description)
3. The 5 essential formulas with their intuitive meaning
4. Links between concepts (e.g., how monetary policy affects inflation)
5. Typical exam questions + approach to answering
Level: second year undergraduate, 3-hour exam. Concise and memorizable."

Creative profile

Creating social media content

Vague prompt:

"Write posts for my Instagram"

Optimized prompt:

"Create 5 Instagram posts for @[account], a yoga studio account in Paris.
Audience: women 25-40, urban, active, practice yoga 1-2x per week.
Theme of the week: yoga and managing work stress.
For each post:
- Main caption (150 words max) with a warm and caring tone
- 3 different hook variations for A/B testing
- 15 relevant hashtags (mix of niche + general)
- Visual idea for the photo or reel
- Recommended optimal posting time
Avoid overly technical yoga jargon. Talk about felt benefits, not poses."

Developing a creative concept

Vague prompt:

"Help me with my creative project"

Optimized prompt:

"I'm developing a podcast about the history of indie video games.
Concept: tell the untold story behind cult games, the struggles,
the pivots, the human stories of the creators.
Help me develop:
1. An episode format (length, structure, type of interviews)
2. 10 episode ideas for season 1 (catchy title + unique angle)
3. A memorable podcast name and its positioning
4. The profile of the first 3 ideal guests (with justification)
5. A 30-second intro for the first episode
References I like: 99% Invisible, How It's Made, Binge Audio."

Table of 15 common mistakes with corrections

Do you recognize these mistakes?

This table covers the most frequent mistakes observed among Claude Code users, from beginner to intermediate. For each mistake: the symptom, the cause, and the correction.

#MistakeSymptomCorrection
1Prompt too vagueUnusable generic resultAdd: stack, context, constraints, expected format
2No technical contextWrong stack or wrong patternAlways specify your stack and conventions
3Asking for everything at onceSuperficial, incomplete codeBreak down into steps of 1-2 responsibilities each
4Starting from scratch each iterationLost context, inconsistent resultsRefine the existing answer with targeted corrections
5Ignoring edge casesCode that crashes in productionExplicitly list edge cases and errors to handle
6Not asking for testsCode without coverage, undetected bugsInclude "generate tests" in every feature prompt
7No CLAUDE.mdRepeating context every sessionCentralize context in CLAUDE.md once and for all
8Unspecified output formatPoorly structured responseAlways specify the format: files, comments, tests
9Contradictory instructionsUnpredictable behaviorCheck the consistency of your constraints before sending
10Constraints buried in textClaude ignores your rulesUse ALWAYS/NEVER in a dedicated section, not inline
11Not verifying resultsUnnoticed bugs or vulnerabilitiesAsk for a self-review before accepting the code
12Prompts without a defined roleOverly generic responsesStart with "You are an expert in [domain]..."
13Asking without showing examplesUnexpected output formatProvide 1-2 examples of the expected result (few-shot)
14Copy-pasting without adaptingCode that doesn't fit the projectCustomize each template with your specific context
15Session too long without /compactClaude "forgets" the beginningUse /compact after each important phase

Beginner mistakes to avoid

The 5 fatal mistakes

These are the most common mistakes among beginners. Avoiding them will save you hours of work.

  1. Being too vague: "Make me something cool" never produces a useful result. Be specific.
  2. Not providing context: Claude can't guess your stack, your architecture, or your conventions.
  3. Asking for everything at once: Break large projects into manageable steps.
  4. Not iterating: If the first answer isn't perfect, refine your request instead of starting over from scratch.
  5. Ignoring output format: If you don't tell Claude how to structure its response, it will choose a default format that may not match your needs.

Next steps

You now have a solid grasp of the prompting fundamentals. To go further: