AI·6 min read·By the StackUtils Team

Prompt Engineering for Developers: Write Better AI Prompts

Learn how to write effective prompts for AI coding assistants. Covers few-shot examples, chain-of-thought reasoning, role prompting, and 10 real patterns that work in production.

Why Prompts Matter More Than the Model

Two developers using the same AI model can get dramatically different results. The difference is almost always the prompt. A poorly structured prompt returns generic, shallow output. A well-structured prompt returns code that matches your stack, handles edge cases, and explains its reasoning.

Prompt engineering is not about memorising magic phrases. It is about applying a small set of principles that help the model understand exactly what you need, the constraints it must work within, and the format you expect.

The Anatomy of a Strong Prompt

Every effective coding prompt has some or all of these components:

RoleTell the model what expert it is acting as

You are a senior TypeScript engineer specialising in Next.js App Router.

ContextProvide the relevant code, tech stack, or background

I have a Next.js 14 app using Prisma and PostgreSQL. Here is my schema: ...

TaskState exactly what you need, clearly and specifically

Write a server action that creates a new user and sends a welcome email.

ConstraintsList rules, patterns, or things to avoid

Use Resend for email. Do not use try/catch — use a Result type instead.

Output formatSpecify the format of the response

Return only the TypeScript code with inline comments. No markdown prose.

6 Core Prompting Techniques

1. Zero-Shot Prompting

Ask directly without examples. Works well for simple, well-defined tasks. Best combined with a clear role and constraints.

You are a senior Go developer. Write a function that validates an email address
using only the standard library. Return true/false. Include unit tests.

2. Few-Shot Prompting

Provide 2–3 examples of the pattern you want. The model infers the pattern and applies it to your actual request. Extremely powerful for enforcing naming conventions or output format.

Convert these API errors to user-friendly messages. Follow this pattern:

Input:  "RESOURCE_NOT_FOUND"
Output: "We couldn't find what you were looking for."

Input:  "RATE_LIMIT_EXCEEDED"
Output: "You're doing that too fast. Please wait a moment."

Now convert: "INVALID_CREDENTIALS"

3. Chain-of-Thought (CoT)

Ask the model to reason step-by-step before writing code. This dramatically reduces logical errors in complex algorithms and architecture decisions.

Before writing any code, think through:
1. What are the edge cases for this input validation?
2. What is the correct order of operations?
3. Which errors must be handled explicitly?

Then write the implementation.

4. Role Prompting

Assigning a specific expert role dramatically improves output quality and tone. Be specific: “senior engineer specialising in distributed systems” gives better results than just “developer”.

You are a security engineer conducting a code review.
Review the following authentication middleware for vulnerabilities.
List each issue with severity (Critical / High / Medium / Low) and a fix.

5. Structured Output

When you need JSON, a specific code format, or a consistent structure, specify it explicitly. For JSON output, you can even provide the schema.

Return your response as JSON matching this TypeScript type:
type Review = {
  summary: string;
  issues: Array<{ line: number; severity: "critical"|"high"|"medium"|"low"; description: string; fix: string }>;
  score: number; // 0-100
}

6. Iterative Refinement

Treat the first response as a draft. Follow up with specific refinements rather than restarting. This preserves context and converges faster.

Good: "The error handling in step 3 is missing — add it without changing anything else."
Bad:  "Can you redo this but better?"

Good: "Change the return type to Promise<Result<User, AppError>>"
Bad:  "Make it async"    // too vague

10 Code-Specific Prompt Patterns That Work

PatternWhen to useKey phrase
Explain like I'm new to thisOnboarding to unfamiliar code"Explain this function step by step"
Write tests first (TDD)Generate implementation from test cases"Write tests for these requirements, then the implementation"
Find the bugDebugging with stack trace"Here is the error and the relevant code. What is wrong?"
Code reviewReviewing your own or team code"Review this for: correctness, edge cases, performance, readability"
Translate patternPort from one language/framework"Rewrite this Python to TypeScript preserving exact behaviour"
Add typesType JavaScript code"Add TypeScript types. Use strict mode assumptions."
Refactor to patternApply a design pattern"Refactor to use the Repository pattern"
Write docsGenerate JSDoc / docstrings"Add JSDoc comments to each exported function"
Generate migrationDB schema changes"Write a Prisma migration for these schema changes"
Optimise querySlow database queries"This query takes 4s. Here's the EXPLAIN output. Suggest optimisations."

5 Common Prompting Mistakes

  1. Being too vague. “Fix my code” gives useless results. Always describe what is broken, what you expected, and what happened instead.
  2. Omitting the tech stack. “Write a login form” could mean React, Vue, plain HTML, or server-side PHP. Always specify your framework, language version, and key libraries.
  3. Asking for too much at once. Splitting a large task into focused sub-tasks produces more accurate results than asking for an entire feature in one prompt.
  4. Trusting without verifying. AI models hallucinate APIs, invent library functions, and produce plausible-looking code with subtle bugs. Always run, review, and test the output.
  5. Not giving context about existing code. Paste the relevant function, type definitions, or schema. The model cannot see your codebase — everything relevant must be in the prompt.

A Reusable Coding Prompt Template

Copy and adapt this template for most coding tasks:

## Role
You are a [senior/expert] [language] developer specialising in [framework/domain].

## Context
[Paste relevant code, schema, error message, or background here]

## Task
[Describe exactly what you need in 1-3 sentences]

## Constraints
- Language/framework: [e.g. TypeScript 5, Next.js 14 App Router]
- Do NOT: [list anything to avoid]
- Must follow: [coding style, patterns, conventions]

## Output format
[e.g. TypeScript code only, no prose / JSON matching <type> / bullet list of changes]

Choose the right AI tool first

Great prompts need the right model. Read our comparison of every major AI coding tool.

AI Coding Tools Guide →