Tutorials6 min read5 May 2026

Writing Better Prompts for Code Generation

How to get AI to write code that actually works in your codebase — not generic boilerplate you have to rewrite anyway.

AI code generation is genuinely transformative — when you prompt it well. Prompt it badly and you get code that compiles but doesn't fit your patterns, uses the wrong libraries, or requires so much editing you might as well have written it yourself.

The most important rule: give it your actual code

Don't describe your codebase. Show it. Paste the relevant files, interfaces, or components. The model can only work with what you give it — generic prompts produce generic code.

A code prompt that works

text
I'm building a Next.js 15 app with TypeScript and Tailwind CSS.
Here's my existing UserCard component:

[paste component]

Here's my user type:

[paste type]

Write a UserList component that renders a grid of UserCards.
Requirements:
- Responsive: 1 col mobile, 2 col tablet, 3 col desktop
- Show empty state if users array is empty
- Loading skeleton state (prop: isLoading)
- Match the existing component's code style exactly

Specify your stack explicitly

Never assume the model knows your stack. Always state: language, framework version, styling approach, state management, and any relevant libraries. "React" could mean class components or hooks. "Styling" could mean CSS modules, Tailwind, or styled-components.

Ask for one thing at a time

"Build me a full authentication system" produces unreliable, sprawling output. Break it down: first the login form, then the API handler, then the session management. Each piece is simpler and easier to verify.

Tell it what to avoid

  • "Don't use any CSS classes that aren't already in my design system"
  • "Don't add comments explaining obvious things"
  • "Don't use any libraries that aren't already in my package.json"
  • "Don't change the function signature"

Review before you run

Always read AI-generated code before running it. Not because it's usually wrong — it's usually right — but because when it is wrong, you need to catch it before it's in production. The review also teaches you what the model did and why, making you better at refining the prompt next time.

The best AI code workflow: prompt → read → test → refine prompt → repeat. The model gets better at your codebase the more context you give it across the conversation.

Test your knowledge

· 4 questions

Sign in to take the quiz

Create an account to test your knowledge, track scores, and mark lessons complete.

🎓Interactive Courses

Ready to go further?

Take the interactive course — daily lessons, real exercises, XP and streaks. Turn reading into lasting skills.

Daily streaksXP & levels
Start a course