Prompt Engineering untuk Developer: Tips dan Template Lengkap
Rabu, 24 Des 2025
AI bukan cuma tools, tapi pair programmer yang available 24/7. Bedanya dengan programmer biasa? Kemampuannya sangat tergantung dari seberapa baik kamu berkomunikasi dengannya.
Itulah kenapa prompt engineering jadi skill penting untuk developer. Artikel ini bakal kasih kamu template siap pakai untuk berbagai skenario coding sehari-hari.
Apa itu Prompt Engineering?
Prompt engineering adalah seni dan ilmu untuk mengkomunikasikan task secara efektif ke AI. Ini bukan sekadar nulis pertanyaan, tapi menyusun instruksi yang jelas, terstruktur, dan lengkap dengan context yang dibutuhkan.
Bayangin kamu brief freelancer untuk sebuah project. Semakin jelas brief-nya, semakin bagus hasilnya. Sama persis dengan AI.
Prinsip Dasar Prompt Engineering
1. Be Specific, Not Vague
❌ "Buatkan function untuk handle data"
✅ "Buatkan TypeScript function bernama `formatUserData` yang:
- Menerima array of user objects dengan field: id, name, email, createdAt
- Return array dengan format: { displayName: string, emailMasked: string, joinDate: string }
- Mask email jadi 'j***@gmail.com'
- Format tanggal jadi 'DD MMM YYYY'"
2. Provide Context
AI nggak tau apa-apa tentang project kamu. Kasih tau:
- Framework/library yang dipakai
- Version yang digunakan
- Conventions yang berlaku di codebase
3. Define Output Format
Mau jawaban dalam bentuk apa? Code only? Step-by-step? Table? Bilang di prompt.
4. Iterate and Refine
Prompt pertama jarang sempurna. Treat ini sebagai conversation, bukan one-shot query.
Anatomy of a Good Prompt
Setiap prompt yang efektif punya 4 komponen ini:
┌─────────────────────────────────────────────────────────────┐
│ CONTEXT │
│ "Saya sedang develop Next.js 14 app dengan TypeScript..." │
├─────────────────────────────────────────────────────────────┤
│ TASK │
│ "Buatkan custom hook untuk infinite scroll..." │
├─────────────────────────────────────────────────────────────┤
│ CONSTRAINTS │
│ "Pakai React Query, handle loading/error states..." │
├─────────────────────────────────────────────────────────────┤
│ OUTPUT FORMAT │
│ "Berikan code lengkap dengan JSDoc comments..." │
└─────────────────────────────────────────────────────────────┘
Mari kita lihat contoh nyatanya:
## Context
Saya develop e-commerce app dengan Next.js 14 (App Router),
TypeScript, dan Tailwind CSS. State management pakai Zustand.
## Task
Buatkan shopping cart feature yang persist ke localStorage.
## Constraints
- Harus type-safe (full TypeScript)
- Handle edge case: item out of stock, max quantity
- Optimistic update untuk UX yang smooth
- Sync dengan backend saat online
## Output Format
1. Zustand store definition
2. Custom hooks untuk akses cart
3. Contoh penggunaan di component
Template Prompts untuk Developer
🐛 Template: Debugging
## Problem
[Deskripsi singkat masalah]
## Error Message
[Paste error message lengkap]
## Relevant Code
```[language]
[Paste code yang bermasalah - include imports]
Environment
- Framework: [Next.js 14 / React 18 / etc]
- Runtime: [Node 20 / Bun / etc]
- Related packages: [package@version]
What I’ve Tried
- [Langkah yang sudah dicoba]
- [Dan hasilnya]
Expected vs Actual Behavior
- Expected: [Apa yang seharusnya terjadi]
- Actual: [Apa yang terjadi]
**Contoh penggunaan:**
```markdown
## Problem
API route return 500 error saat fetch products
## Error Message
TypeError: Cannot read properties of undefined (reading ‘map’) at GET (app/api/products/route.ts:15:23)
## Relevant Code
```typescript
import { prisma } from '@/lib/prisma'
export async function GET() {
const products = await prisma.product.findMany()
const formatted = products.data.map(p => ({
id: p.id,
name: p.name
}))
return Response.json(formatted)
}
Environment
- Next.js 14.0.4
- Prisma 5.7.0
- Node 20
What I’ve Tried
- Cek database connection - OK
- Run
prisma.product.findMany()di script terpisah - work
Expected vs Actual
- Expected: Return JSON array of products
- Actual: 500 Internal Server Error
### 🔍 Template: Code Review
```markdown
## Code untuk Review
```[language]
[Paste code]
Context
- Ini adalah [jenis feature/component]
- Akan di-deploy ke [production/staging]
- Expected traffic: [info jika relevant]
Review Focus
Tolong review dari sisi:
- ⚡ Performance - ada bottleneck?
- 🔒 Security - ada vulnerability?
- 🧹 Code quality - readability, maintainability
- 🐛 Bug potential - edge cases yang missed?
- 📏 Best practices - sesuai [framework] conventions?
Output Format
Untuk setiap issue, berikan:
- 🔴 Critical / 🟡 Warning / 🟢 Suggestion
- Lokasi issue (line/function)
- Penjelasan kenapa ini issue
- Contoh code yang sudah diperbaiki
### ♻️ Template: Refactoring
```markdown
## Current Code
```[language]
[Paste code yang mau di-refactor]
Problems dengan Code Ini
- [Problem 1: e.g., terlalu banyak responsibilities]
- [Problem 2: e.g., hard to test]
- [Problem 3: e.g., duplicate logic]
Refactoring Goals
- [Goal 1: e.g., pisahkan ke smaller functions]
- [Goal 2: e.g., tambahkan proper error handling]
- [Goal 3: e.g., buat lebih testable]
Constraints
- Jangan ubah public API / function signature
- Tetap compatible dengan [existing code]
- Pakai pattern: [e.g., Repository pattern]
Output
- Refactored code dengan comments yang jelasin perubahan
- Before/after comparison untuk setiap perubahan major
- Potential breaking changes (jika ada)
### 🏗️ Template: Generate Boilerplate
```markdown
## What to Generate
[Jenis boilerplate: API route, React component, etc]
## Specifications
- Name: [nama file/component]
- Location: [path di project]
- Purpose: [apa fungsinya]
## Tech Stack
- Framework: [Next.js / Remix / etc]
- Language: [TypeScript / JavaScript]
- Styling: [Tailwind / CSS Modules / etc]
- State: [Zustand / Redux / etc]
- Validation: [Zod / Yup / etc]
## Features Required
1. [Feature 1 dengan detail]
2. [Feature 2 dengan detail]
3. [Feature 3 dengan detail]
## Code Style
- [Conventions: e.g., named exports, functional components]
- [Formatting: e.g., single quotes, trailing commas]
## Example of Similar Code in Codebase
```[language]
[Paste contoh code sejenis dari project untuk reference style]
**Contoh penggunaan:**
```markdown
## What to Generate
React component untuk product card di e-commerce
## Specifications
- Name: ProductCard
- Location: components/product/ProductCard.tsx
- Purpose: Display product info di listing page
## Tech Stack
- Next.js 14 (App Router)
- TypeScript (strict mode)
- Tailwind CSS
- Zustand untuk cart state
## Features Required
1. Display: image, title, price, rating, discount badge
2. Hover state: quick add to cart button muncul
3. Skeleton loading state
4. Responsive: 2 cols mobile, 4 cols desktop
## Code Style
- Named exports
- Interface untuk props di file yang sama
- Tailwind classes, no inline styles
- Compound component pattern jika perlu sub-components
📝 Template: Write Documentation
## Code to Document
```[language]
[Paste code]
Documentation Type
[JSDoc / README / API docs / Inline comments]
Audience
[Junior devs / External API consumers / Internal team]
Documentation Should Include
- Function/component description
- Parameters dengan types dan description
- Return value
- Usage examples
- Edge cases / gotchas
- Related functions/components
Format
[Markdown / JSDoc / TSDoc]
Example of Existing Docs in Project
[Paste contoh dokumentasi yang sudah ada]
### 🎓 Template: Explain Code
```markdown
## Code to Explain
```[language]
[Paste code]
My Understanding Level
[Beginner / Intermediate / Advanced] in [language/framework]
Specific Questions
- [Pertanyaan spesifik 1]
- [Pertanyaan spesifik 2]
Explanation Format
Tolong jelaskan dengan:
- Summary singkat (1-2 kalimat)
- Step-by-step breakdown
- Analogi sederhana (jika concept complex)
- Diagram/visual (jika applicable)
- Common use cases
- Potential pitfalls
### 🔄 Template: Convert Code Between Languages
```markdown
## Source Code
```[source_language]
[Paste original code]
Convert To
[target_language] dengan [framework jika ada]
Maintain
- Same functionality
- Similar structure
- Idiomatic style untuk target language
- Error handling approach
- Type safety level
Target Environment
- Runtime: [Node / Deno / Bun / Browser]
- Version: [target_language version]
- Dependencies available: [list libraries yang boleh dipakai]
Additional Requirements
- [Requirement 1: e.g., async/await style]
- [Requirement 2: e.g., specific naming convention]
**Contoh penggunaan:**
```markdown
## Source Code
```python
def fetch_user_data(user_id: str) -> dict:
try:
response = requests.get(f"{API_URL}/users/{user_id}")
response.raise_for_status()
data = response.json()
return {
"id": data["id"],
"name": data["full_name"],
"email": data["email_address"]
}
except requests.RequestException as e:
logger.error(f"Failed to fetch user: {e}")
raise UserFetchError(f"Could not fetch user {user_id}")
Convert To
TypeScript dengan modern Node.js
Maintain
- Same functionality
- Idiomatic TypeScript style
- Proper error handling
Target Environment
- Runtime: Node 20
- Available: fetch (native), zod for validation
Additional Requirements
- Pakai native fetch (no axios)
- Return type harus strongly typed (no any)
- Tambahkan input validation
## Chain Prompting untuk Task Kompleks
Untuk task besar, pecah jadi beberapa prompt berurutan:
### Contoh: Build Feature End-to-End
**Prompt 1: Planning**
```markdown
Saya mau build comment system untuk blog dengan:
- Nested replies (max 3 levels)
- Like/unlike comments
- Real-time updates
- Markdown support
Tech stack: Next.js 14, Prisma, PostgreSQL
Tolong buatkan:
1. Database schema design
2. API endpoints yang dibutuhkan
3. Component hierarchy
4. State management approach
Jangan tulis code dulu, fokus ke architecture.
Prompt 2: Implementation (setelah approve architecture)
Based on architecture di atas, sekarang implement:
1. Prisma schema untuk comments
[Paste architecture dari prompt sebelumnya untuk context]
Prompt 3: Continue Implementation
Sekarang implement API routes untuk:
- GET /api/comments (with pagination)
- POST /api/comments (create new)
- PATCH /api/comments/:id (edit)
- DELETE /api/comments/:id
Pakai schema dan conventions dari sebelumnya:
[Paste relevant code dari prompt sebelumnya]
Prompt 4: Testing
Buatkan test cases untuk API routes yang sudah dibuat:
[Paste API route code]
Testing framework: Vitest
Mocking: msw untuk API calls
Coverage target: happy path + error cases
Tips: Iterasi dan Refine Prompts
Teknik 1: Follow-up yang Efektif
Kamu: [Initial prompt]
AI: [Response dengan code]
Kamu: "Bagus, tapi tolong:
1. Tambahkan loading state
2. Handle case kalau array kosong
3. Pisahkan styles ke file terpisah"
Teknik 2: Minta Alternatif
"Kasih 3 pendekatan berbeda untuk solve ini, dengan pros/cons masing-masing"
Teknik 3: Challenge AI
"Apa potential issues dengan approach ini?
Gimana cara handle kalau data sangat besar?"
Teknik 4: Ask for Improvement
"Kamu developer senior. Review code yang baru kamu kasih.
Apa yang bisa di-improve?"
Common Mistakes dan Cara Menghindarinya
❌ Mistake 1: Prompt Terlalu Pendek
"Fix bug di code ini"
Kenapa jelek: AI nggak tau context, error apa, environment apa.
✅ Fix: Pakai template debugging di atas.
❌ Mistake 2: Terlalu Banyak Task Sekaligus
"Buatkan authentication system lengkap dengan login, register,
forgot password, OAuth, role-based access, dan audit logging"
Kenapa jelek: AI overwhelmed, result akan shallow dan incomplete.
✅ Fix: Pecah jadi multiple prompts dengan chain prompting.
❌ Mistake 3: Tidak Specify Tech Stack
"Buatkan API untuk user management"
Kenapa jelek: AI mungkin generate pakai framework yang berbeda dari project kamu.
✅ Fix: Selalu include tech stack dan version.
❌ Mistake 4: Copy-Paste Tanpa Review
AI bisa generate code yang:
- Pakai deprecated API
- Ada security vulnerability
- Nggak efficient untuk scale besar
- Nggak sesuai project conventions
✅ Fix: SELALU review, test, dan pahami code sebelum commit.
❌ Mistake 5: Tidak Kasih Contoh
"Buatkan component dengan style yang sama dengan yang lain"
Kenapa jelek: AI nggak bisa baca codebase kamu (kecuali pakai Cursor @codebase).
✅ Fix: Paste contoh code yang similar sebagai reference.
❌ Mistake 6: Expect AI Perfect di First Try
✅ Fix: Treat sebagai conversation. Iterate dan refine.
Quick Reference: Prompt Starters
| Use Case | Prompt Starter |
|---|---|
| Debug | ”Saya dapat error [X] saat [Y]. Code: …” |
| Explain | ”Jelaskan step-by-step cara kerja code ini: …” |
| Refactor | ”Refactor code ini untuk [goal]. Constraints: …” |
| Generate | ”Buatkan [apa] dengan specs: …” |
| Review | ”Review code ini dari sisi [aspects]: …” |
| Convert | ”Convert code ini dari [A] ke [B]: …” |
| Optimize | ”Optimize code ini untuk [performance/readability]: …” |
| Test | ”Buatkan test cases untuk code ini dengan [framework]: …” |
Kesimpulan
Prompt engineering bukan magic, tapi skill yang bisa diasah. Key takeaways:
- Structure matters - Pakai format CONTEXT + TASK + CONSTRAINTS + OUTPUT
- Be specific - Semakin detail prompt, semakin bagus output
- Iterate - First prompt jarang sempurna, dan itu OK
- Provide examples - Paste existing code sebagai reference
- Chain for complexity - Pecah task besar jadi steps
- Always review - AI adalah assistant, bukan replacement
Start dengan template di atas, customize sesuai kebutuhan, dan terus refine berdasarkan experience.
Template di artikel ini bisa kamu bookmark dan pakai langsung. Punya template favorit sendiri? Share di Twitter @nayakayp!