How to Write Perfect Prompts for ChatGPT Code Generation (with Examples)
Master the art of writing effective ChatGPT prompts for coding. 10 before/after examples, proven frameworks, and templates that get you production-ready code faster.
- The SPEC Framework
- S - Be Specific
- Example 1: API Endpoint Creation
- Example 2: Database Query
- P - Project-Aware (Context is King)
- Example 3: React Component
- Example 4: Python Script
- E - Provide Examples
- Example 5: Error Handling
- Example 6: Test Cases
- C - Set Constraints
- Example 7: No External Dependencies
- Example 8: Performance Requirements
- The Complete Template
- Advanced Techniques
- Multi-Step Prompts
- Iterative Refinement
- Code Review Prompts
- Common Mistakes to Avoid
- Mistake 1: Not Providing Error Messages
- Mistake 2: Asking for Code Without Context
- Mistake 3: Not Specifying Output Format
- Real-World Examples
- Example 9: Debugging Production Issue
- Example 10: Refactoring Legacy Code
- Measuring Prompt Effectiveness
- Tools to Automate Perfect Prompts
- Quick Reference: Prompt Templates
- Bug Fix Template
- Feature Request Template
- Performance Optimization Template
- Key Takeaways
- Practice Exercise
- Answer to Practice Exercise
Bad prompts waste hours. Good prompts save them.
After analyzing 500+ ChatGPT coding conversations, I've discovered the exact patterns that consistently produce production-ready code on the first try.
This guide shows you the framework, with 10 real before/after examples you can copy today.
The SPEC Framework
Every great ChatGPT coding prompt has four elements:
S - Specific (exact requirements)
P - Project-aware (your tech stack)
E - Examples (show, don't tell)
C - Constraints (what NOT to do)
Let's break down each element.
S - Be Specific
Vague prompts get vague responses. Specificity is your superpower.
Example 1: API Endpoint Creation
❌ Bad Prompt:
Create a user login endpoint
✅ Good Prompt:
Create a POST /auth/login endpoint that:
- Accepts email and password
- Returns JWT token on success
- Returns specific error codes: 401 (invalid credentials), 429 (rate limited)
- Token expires in 24 hours
- Include refresh token logic
Result: First response included complete implementation with error handling, rate limiting, and security best practices.
Example 2: Database Query
❌ Bad Prompt:
Get all users from database
✅ Good Prompt:
Write a PostgreSQL query that:
- Fetches users with their associated posts
- Only includes users active in last 30 days
- Sorts by post count (descending)
- Limits to 50 results
- Includes pagination offset parameter
Result: Optimized query with proper indexes suggested.
P - Project-Aware (Context is King)
ChatGPT doesn't know your tech stack unless you tell it.
Example 3: React Component
❌ Bad Prompt:
Create a form component
✅ Good Prompt:
Create a form component for our Next.js 15 app (App Router):
Tech stack:
- Next.js 15 with server actions
- TypeScript (strict mode)
- Tailwind CSS for styling
- React Hook Form for validation
- Zod for schema validation
The form should submit to a server action and show loading states.
Result: Component with proper TypeScript types, server action integration, and loading UI.
Example 4: Python Script
❌ Bad Prompt:
Write a script to process CSV files
✅ Good Prompt:
Write a Python 3.11 script that:
- Uses pandas for CSV processing
- Works with files up to 1GB
- Runs in AWS Lambda (512MB memory limit)
- Handles missing data gracefully
- Outputs to S3 bucket
Input format: user_id,email,signup_date
Output: aggregated daily signups
Result: Memory-efficient script with proper error handling and S3 integration.
E - Provide Examples
Show ChatGPT what you want with concrete examples.
Example 5: Error Handling
❌ Bad Prompt:
Add error handling to this function
✅ Good Prompt:
Add error handling to this function. Our error format is:
{
success: false,
error: {
code: "ERR_VALIDATION",
message: "User-friendly message",
details: { field: "email", reason: "invalid_format" }
}
}
Current function:
[paste code]
Handle these cases: validation errors, network errors, database errors
Result: Consistent error handling that matches your existing patterns.
Example 6: Test Cases
❌ Bad Prompt:
Write tests for this function
✅ Good Prompt:
Write Jest tests for this authentication function.
Example test from our codebase:
describe('validateEmail', () => {
it('should accept valid email', () => {
expect(validateEmail('user@example.com')).toBe(true);
});
it('should reject invalid format', () => {
expect(validateEmail('invalid')).toBe(false);
});
});
Follow this pattern. Test cases needed:
- Valid credentials
- Invalid password
- Non-existent user
- Rate limit exceeded
- Database connection error
Result: Tests that match your existing test suite style.
C - Set Constraints
Tell ChatGPT what NOT to do.
Example 7: No External Dependencies
❌ Bad Prompt:
Sort this array of objects
✅ Good Prompt:
Sort this array of objects by 'createdAt' date (newest first).
Constraints:
- No external libraries (lodash, moment, etc.)
- Must work in Node.js 18+
- Maintain original array immutability
- Handle invalid dates gracefully
Array: [paste data]
Result: Pure JavaScript solution without dependencies.
Example 8: Performance Requirements
❌ Bad Prompt:
Optimize this slow function
✅ Good Prompt:
This function processes 100k records and takes 8 seconds. Optimize it to run under 1 second.
Constraints:
- Must be O(n) or better
- Can't use caching (data changes frequently)
- Must maintain exact same output
- Memory limit: 512MB
Current code:
[paste code]
Result: Optimized algorithm with complexity analysis.
The Complete Template
Here's the ultimate ChatGPT coding prompt template:
I'm building [type of application] with [tech stack].
Task: [specific requirement]
Tech Context:
- Language/Framework: [details]
- Dependencies: [list key dependencies]
- Environment: [development/production, platform]
Requirements:
1. [specific requirement 1]
2. [specific requirement 2]
3. [specific requirement 3]
Example of our coding patterns:
[paste example if available]
Constraints:
- [what NOT to do]
- [performance requirements]
- [compatibility requirements]
Current code (if updating):
[paste code]
Expected output:
[describe what success looks like]
Advanced Techniques
Multi-Step Prompts
For complex tasks, break into steps:
Step 1:
I need to build a file upload system. First, help me design the architecture.
Requirements: [list requirements]
Step 2:
Based on that architecture, now write the upload handler function.
Use the S3 approach we discussed. Include:
- Presigned URL generation
- Progress tracking
- Error handling
Step 3:
Now write the frontend component that uses this upload handler.
Framework: React + TypeScript
Show upload progress with a progress bar.
Iterative Refinement
Start broad, get specific:
Iteration 1:
What are the best approaches for implementing real-time notifications in a web app?
Iteration 2:
Using the WebSocket approach, how do I implement it with Socket.io in Node.js?
Iteration 3:
Add authentication to those WebSocket connections using JWT tokens.
Code Review Prompts
❌ Bad:
Review this code
✅ Good:
Review this authentication middleware for:
1. Security vulnerabilities
2. Performance issues (handles 1000 req/sec)
3. TypeScript best practices
4. Error handling completeness
Our stack: Express.js, TypeScript, JWT auth
Production environment: AWS ECS
Code:
[paste code]
Common Mistakes to Avoid
Mistake 1: Not Providing Error Messages
Bad:
My code isn't working
Good:
Getting "TypeError: Cannot read property 'map' of undefined" at line 42.
The data comes from this API: [endpoint]
Expected format: { users: [...] }
What I'm receiving: [paste actual response]
Code:
[paste relevant code]
Mistake 2: Asking for Code Without Context
Bad:
Write a caching function
Good:
Write a caching function for our Redis setup.
Use case: Cache API responses for 5 minutes
Tech: Node.js, ioredis library
Handle these scenarios:
- Cache miss (fetch from API)
- Cache hit (return cached)
- Cache invalidation on POST/PUT/DELETE
- Handle Redis connection errors gracefully
Mistake 3: Not Specifying Output Format
Bad:
Generate API documentation
Good:
Generate OpenAPI 3.0 documentation for this endpoint.
Format: YAML
Include: request/response schemas, error codes, examples
Follow this example from our docs:
paths:
/users:
get:
summary: "List users"
responses:
200:
description: "Success"
content:
application/json:
schema:
$ref: '#/components/schemas/UserList'
Real-World Examples
Example 9: Debugging Production Issue
Effective Debugging Prompt:
Production bug: Users can't upload files > 5MB
Environment:
- Next.js 15 (App Router)
- Vercel deployment
- Files stored in AWS S3
Error in logs: "PayloadTooLargeError"
Steps to reproduce:
1. User selects 6MB file
2. Upload starts
3. Fails at ~80% progress
4. Error shown to user
Relevant code:
[paste upload handler]
What's causing this and how do I fix it?
Result: Identified Vercel's body size limit, provided solution with presigned S3 URLs.
Example 10: Refactoring Legacy Code
Effective Refactoring Prompt:
Refactor this legacy code to modern JavaScript:
Current: ES5, callbacks, no error handling
Target: ES2022, async/await, proper error handling
Constraints:
- Must maintain exact same functionality
- Can't change function signature (used by 50+ files)
- Must be backwards compatible with Node.js 16+
Current code:
[paste code]
Our modern code style (example):
[paste example]
Result: Clean refactored code that maintained compatibility.
Measuring Prompt Effectiveness
Track these metrics:
- Iterations to Working Code
- - Target: ≤ 2 iterations
- - Bad prompts: 5+ iterations
- Code Quality
- - First response production-ready?
- - Needed refactoring?
- Time Saved
- - Good prompt: 5 minutes to solution
- - Bad prompt: 30+ minutes of back-and-forth
Tools to Automate Perfect Prompts
Writing perfect prompts every time is exhausting. ThoughtTap automates this:
- Analyzes your codebase automatically
- Detects tech stack, frameworks, patterns
- Generates SPEC-compliant prompts
- Works with ChatGPT, Claude, Gemini, any AI
Before ThoughtTap:
// Your manual prompt
"Create a login function"
// Result: Generic, doesn't match your stack
With ThoughtTap:
// Auto-generated prompt
"Create a login function for Next.js 15 app router using server actions.
Tech context:
- Framework: Next.js 15 (App Router)
- Auth: NextAuth.js
- Database: Prisma + PostgreSQL
- Validation: Zod
- Error format: { success: boolean, error?: {...} }
Requirements:
[automatically detects from your codebase patterns]
"
// Result: Perfect code, first try
Quick Reference: Prompt Templates
Bug Fix Template
Bug: [specific issue]
Error: [full error message + stack trace]
Environment: [tech stack]
Steps to reproduce: [1, 2, 3]
Expected: [what should happen]
Actual: [what's happening]
Code: [relevant code]
Feature Request Template
Feature: [what you're building]
Tech stack: [your stack]
Requirements: [numbered list]
Constraints: [what to avoid]
Existing patterns: [example code]
Performance Optimization Template
Function: [description]
Current performance: [metrics]
Target performance: [goal]
Constraints: [memory, complexity, compatibility]
Code: [paste code]
Key Takeaways
- Use the SPEC Framework - Specific, Project-aware, Examples, Constraints
- Always include tech stack - ChatGPT can't guess your environment
- Show examples - Especially for code style and patterns
- Set clear constraints - Prevent unwanted solutions
- Iterate methodically - Break complex tasks into steps
- Measure effectiveness - Track iterations to working code
- Automate when possible - Use ThoughtTap for consistent results
Practice Exercise
Try transforming this bad prompt:
❌ Bad:
Make a todo app
✅ Your turn - include: - Specific features needed - Your tech stack - Code style example - What to avoid
Example answer at the end of this article.
Answer to Practice Exercise
✅ Good Prompt:
Create a todo list app for Next.js 15 (App Router).
Tech Stack:
- Next.js 15 with server actions
- TypeScript (strict mode)
- Prisma + PostgreSQL
- Tailwind CSS
Features:
- Add/edit/delete todos
- Mark as complete
- Filter: all, active, completed
- Persist to database
Our code style (example):
export async function createTodo(formData: FormData) {
'use server'
const title = formData.get('title') as string
try {
await prisma.todo.create({ data: { title } })
revalidatePath('/todos')
return { success: true }
} catch (error) {
return { success: false, error: 'Failed to create todo' }
}
}
Constraints:
- No client-side state (use server state)
- Form must work without JavaScript
- Follow our error pattern above
Result: Production-ready todo app with proper patterns.
Ready to write perfect prompts every time? Try ThoughtTap →
What's your biggest prompt challenge? Share in the comments! Got a great prompt template? Let's see it! 🚀