Prompt Templates That Ship Code
Ten prompt recipes for React, APIs, schemas, tests, refactors, debugging, reviews, and CI.
A throwaway prompt gets you throwaway code. A precise one gets you something you can actually merge. The gap between the two is almost always specificity. Fuzzy instructions breed fuzzy output.
The ten recipes below bake in the detail Claude Code needs to produce work you'd hand off for review. Each one ships with the prompt, the reason it holds up, a few swap-outs for other stacks, and the failure modes that hit people who reach for something similar without any structure.
Project Scaffolding
Full-Stack Web App
claude "Create a React app with TypeScript and Tailwind CSS. It's a todo app with localStorage persistence. Include: add, edit, delete, mark complete, and filter by status (all/active/completed). Use a single TodoContext for state management. Make it mobile-responsive with min-width 320px support."
Why it lands: Tech stack, storage choice, every CRUD verb, the state model, and the smallest supported screen size are all written out. Claude stops guessing, so nothing comes back that you'll need to rip out later.
Swap-outs:
- Next.js: swap "React app" for "Next.js 15 app using App Router and Server Components where possible"
- Vue: replace the React/TypeScript stack with "Vue 3 with Composition API and TypeScript"
- Richer starter: tack on "Include dark mode toggle, keyboard shortcuts (Ctrl+N for new, Delete to remove), and export/import as JSON"
Where people go wrong: A bare "create a todo app" pushes Claude to default to whatever feels right, which rarely matches your repo. "Make it look good" is worse than naming Tailwind, because taste is not a spec.
What you get back: three to five files. A React component tree, a context provider, TypeScript interfaces for the todo model, and a Tailwind layout that flexes. npm run dev runs it on the first try.
API Backend with Auth
claude "Build an Express.js REST API with JWT authentication. Include: user registration (POST /auth/register), login (POST /auth/login), and a protected endpoint (GET /auth/me). Hash passwords with bcrypt (12 rounds). Use middleware for token verification. Add Zod validation for request bodies. Return consistent JSON error responses with status codes. Include a health check endpoint at GET /health."
Why it lands: Writing out the routes stops Claude from inventing its own. Naming the bcrypt round count, the validation library, and the error shape means the output already looks like code from your project. No cleanup pass.
Swap-outs:
- Fastify: replace "Express.js" with "Fastify with @fastify/jwt plugin"
- Prisma: add "Use Prisma with PostgreSQL. Include a User model with id, email, passwordHash, createdAt fields"
- Sessions: trade "JWT authentication" for "express-session with Redis store for session management"
Where people go wrong: Skip the error handling line and Claude writes only the happy path. Registration and login work with clean input, and blow up on anything malformed.
Database and Data Layer
Schema Generation
claude "Create a PostgreSQL schema for a multi-tenant SaaS app. Tables needed: organizations, users (belongs to organization), projects (belongs to organization), and tasks (belongs to project, assigned to user). Include: UUID primary keys, created_at/updated_at timestamps on all tables, proper foreign keys with ON DELETE CASCADE, a unique constraint on user email per organization, and indexes on all foreign key columns. Add 5 sample INSERT statements per table for testing."
Why it lands: The word "multi-tenant" carries the isolation pattern. Calling out UUID keys, timestamps, cascade rules, and the scope of the unique email constraint kills the most common review nits. Asking for sample rows forces the schema to actually load without errors.
Swap-outs:
- MySQL: replace "PostgreSQL" with "MySQL 8.0 using InnoDB engine"
- Prisma migrations: add "Format as Prisma schema instead of raw SQL, and generate the initial migration"
- Audit log: add "Include an events table with a JSONB payload column, indexed with GIN, for audit logging"
Testing
Full Test Setup
claude "Set up Vitest with React Testing Library for this TypeScript React project. Create: a test for the Button component that checks rendering, click handling, disabled state, and loading state. An integration test for the LoginForm that mocks the auth API call, fills the form, submits, and verifies redirect on success and error message on failure. Add a test utility file with a renderWithProviders function that wraps components in the app's context providers. Add test and test:coverage scripts to package.json."
Why it lands: Test prompts fall over when they read like "write tests for this component." Here you get four named cases for the unit test and two end-to-end flows for the integration test. The shared helper file is the piece most people skip, and it's the piece that keeps future tests consistent.
Swap-outs:
- Playwright E2E: replace the framework with "Set up Playwright for end-to-end testing. Include a test that navigates to the login page, fills credentials, submits, and verifies the dashboard loads"
- API testing: "Set up Supertest with Vitest for the Express API. Test the /auth/register endpoint with valid data, duplicate email, and missing required fields"
What you get back: a config file, two or three test files that pass, a shared utilities file, and fresh package.json scripts. npm test goes green right away.
Refactoring
Component Decomposition
claude "This UserDashboard component is 400 lines long. Refactor it by: extracting the stats cards into a StatsGrid component, the activity feed into an ActivityFeed component, and the sidebar navigation into a DashboardNav component. Keep the data fetching in UserDashboard and pass data down as props. Create TypeScript interfaces for all props. Preserve all existing functionality and don't change any CSS class names."
Why it lands: Refactor prompts need guardrails. "Refactor this component" lets Claude move anything it wants, and behavior quietly shifts. Spelling out which children to pull out, where fetching stays, and which CSS classes stay put means the new code drops into your app without breaking the UI or the tests.
Swap-outs:
- Custom hook: "Extract the data fetching logic into a useUserDashboard custom hook. Return the loading state, error state, and all data objects. Keep the component purely presentational"
- Zustand migration: "Move the local useState calls into a Zustand store. Export typed selectors for each piece of state. Keep the component renders identical"
Debugging
Structured Bug Hunt
claude "Users report that the checkout form submits twice on slow connections. Investigate: check the form's onSubmit handler for missing event.preventDefault() or missing disabled state during submission. Check if the submit button lacks a loading/disabled state. Check for React StrictMode double-render issues. Check if the API call has retry logic that could cause duplicates. Propose a fix and add an idempotency safeguard."
Why it lands: Most debugging prompts read "fix this bug." That asks Claude to guess, grep, and patch in one go, and usually it locks onto the first plausible story. This version hands over the four likeliest root causes for a double submit and asks Claude to walk through each one in order.
Swap-outs:
- Slow page: "The dashboard takes 8 seconds to load. Investigate: check for N+1 queries in the API, unnecessary re-renders in React components, unoptimized images, and missing database indexes. Measure the time each fix saves"
- Auth drop: "Users are getting logged out randomly. Check: JWT expiration handling, refresh token rotation, cookie settings (SameSite, Secure, HttpOnly), and whether concurrent requests race on token refresh"
Code Review and Quality
Pre-PR Review
claude "Review the changes in this branch for a PR. Check for: security issues (SQL injection, XSS, exposed secrets), missing error handling on async operations, TypeScript type safety (no 'any' types, proper null checks), accessibility on any new UI components (ARIA labels, keyboard navigation), and performance concerns (unnecessary re-renders, missing useMemo/useCallback). Format findings as a list with severity (critical/warning/info) and file location."
Why it lands: "Review this code" gets surface-level notes. Spelling out the five review axes and the output shape yields a report you can walk down and action right away.
Swap-outs:
- Backend only: swap accessibility and re-renders for "N+1 queries, missing rate limiting, and improper error propagation"
- Security pass: "Focus exclusively on security: check all user inputs, authentication boundaries, authorization checks, sensitive data handling, and dependency vulnerabilities"
Feature Development
Vertical Slice Build
claude "Add a comment system to blog posts. Requirements: comments stored in a PostgreSQL comments table with id, post_id, author_name, content, created_at. API endpoints: GET /posts/:id/comments and POST /posts/:id/comments with Zod validation. React component showing threaded comments with a reply form. Optimistic UI update on new comment submission. Rate limit to 5 comments per minute per IP. Include the database migration."
Why it lands: The prompt spans the whole slice. Table, API, and UI in a single request. Naming optimistic rendering, the rate limit, and the migration file means Claude writes the feature as one finished unit, not three loosely related fragments that expose gaps at test time.
Swap-outs:
- Real-time: "Add WebSocket support so new comments appear for all viewers without refreshing"
- Moderation: "Include an isApproved boolean field and an admin endpoint to approve/reject comments"
Infrastructure and DevOps
CI/CD Pipeline
claude "Create a GitHub Actions workflow for this TypeScript monorepo. On push to main: run TypeScript type checking, run Vitest tests, build the Next.js app, and deploy to Vercel. On pull request: run type checking and tests only, post a preview deployment link as a PR comment. Cache node_modules between runs using pnpm lockfile hash. Fail fast if any step errors."
Why it lands: Pipeline prompts need branch rules written up front. By splitting what runs on main from what runs on PRs, calling out the cache key, and naming the preview behavior, the workflow lands correctly on the first push. No three rounds of "oh, also add this."
Swap-outs:
- Docker: "Build and push a Docker image to GitHub Container Registry on main, tagged with the git SHA and 'latest'"
- Migrations: "Add a step that runs Prisma migrations against the staging database before deployment, with a rollback step if deployment fails"
Configuration and Environment
Config Audit
claude "Audit this project's configuration. Check: tsconfig.json has strict mode enabled and proper path aliases. ESLint config catches unused imports, consistent formatting, and React hook dependency warnings. Package.json has correct scripts for dev, build, test, and lint. Environment variables are validated at startup (not just process.env access scattered through code). Flag any configuration that could cause silent failures in production."
Why it lands: Config bugs are the worst kind. They fail quietly or only on Tuesdays. This prompt points Claude at the four surfaces that matter and asks directly about production failure modes.
Usage Principles
The ten recipes hold up for three reasons worth stealing.
Ship the shape, not just the goal. "Create an API" is a goal. "Create Express endpoints at these routes with Zod validation and consistent error responses" is a shape. Claude works back from the shape and builds to match it.
Name the constraints up front. Any constraint you leave unsaid turns into a coin flip. Stack, error handling, styling, browser support, database engine. If it matters, write it down. If you don't, Claude picks whatever looks fine.
Write down the boring requirements. Rate limiting. Idempotency. Loading states. Error boundaries. Accessible labels. These are the lines that separate a demo from real code, and they're the ones most prompts leave out. Spending a few extra words on them saves hours of rework later.
Build Your Own Library
The ten recipes cover patterns that show up on almost every project. Your codebase has its own shape though, and its own sharp edges. The payoff comes from keeping a template library of your own. When a Claude Code run produces something clean, save the prompt. When it doesn't, figure out which piece of the spec was missing and bolt it on.
Stop configuring. Start building.
Human-like Agents
Personality patterns for Claude Code agents: reasoning out loud, admitting uncertainty, weighing trade-offs, asking follow-up questions.
Claude Code Troubleshooting
Resolve install errors, bad API keys, 503 timeouts, slow replies, and permission trouble. Five ordered checks clear the common breakage paths.