30 Battle-Tested Prompts for Claude Code: From Refactoring to Architecture
If you use Claude Code in your daily workflow, you know the difference between a vague prompt and a precise one can be hours of wasted time. Over the past year, I've collected and refined dozens of prompts that actually work — not theoretical examples from documentation, but real prompts I use to review, refactor, and design code. This article compiles 30 of them, organized by task type, with real usage examples and context.
Why These Prompts Work
Claude Code, unlike general-purpose LLMs, is optimized for code understanding and generation. It can handle large codebases, track context across files, and execute commands. The prompts below leverage these capabilities by being:
- Context-aware: They specify which files, functions, or patterns to focus on.
- Action-oriented: They tell Claude exactly what to do (review, rewrite, suggest).
- Constraint-driven: They set boundaries (languages, frameworks, performance goals).
How to Use This List
Each prompt includes a usage example — a real scenario where I applied it. You can copy-paste directly, but adjust file paths and project specifics. Prompts are grouped into categories:
| Category | Focus |
|---|---|
| Code Review | Static analysis, security, style |
| Refactoring | Performance, readability, maintainability |
| Architecture | Design patterns, system design, migrations |
| Testing | Unit tests, integration tests, coverage |
| Documentation | Inline comments, README, API docs |
Code Review Prompts
1. Security Audit
Prompt: "Review src/auth/login.ts for OWASP Top 10 vulnerabilities. Focus on SQL injection, XSS, and insecure deserialization. List each issue with severity (critical/high/medium/low) and a fix suggestion."
Usage Example: I ran this on a legacy Express.js authentication module. Claude found a raw SQL query with string interpolation (critical — SQL injection) and suggested parameterized queries with pg library.
2. Performance Bottleneck Detection
Prompt: "Analyze src/api/products.ts for N+1 queries and unnecessary re-renders. Identify the top 3 performance bottlenecks and propose optimizations using caching or batch loading."
Usage Example: In a Node.js API with Prisma ORM, Claude detected nested loops calling the database inside a map — classic N+1. It suggested include and batch queries, reducing response time from 2.3s to 0.4s.
3. Code Style Compliance
Prompt: "Check src/components/*.tsx against our ESLint config (.eslintrc.json). List all violations with line numbers, and auto-fix where possible. Use eslint --fix but report unfixable issues."
Usage Example: Claude executed eslint in the project, parsed the output, and created a list of 12 violations — 8 auto-fixed, 4 requiring manual attention (e.g., unused imports).
4. Dependency Review
Prompt: "Review package.json for outdated or vulnerable dependencies. Use npm audit and npm outdated. Suggest upgrades and note breaking changes."
Usage Example: Claude ran npm audit, found 3 high-severity vulnerabilities in lodash and axios. It suggested version bumps and tested compatibility with existing code.
5. Logging and Error Handling
Prompt: "Check src/services/payment.ts for missing error handling and insufficient logging. Add structured logs (with correlation IDs) and try-catch blocks where needed."
Usage Example: In a Stripe integration, Claude added try-catch around webhook handlers and included stripeEventId in every log line, making debugging in production much easier.
Refactoring Prompts
6. Function Decomposition
Prompt: "Refactor src/utils/parser.ts — break the 300-line parseDocument function into smaller, single-responsibility functions. Each new function must have a JSDoc comment and unit tests."
Usage Example: Claude split a monolithic parser into tokenize, buildAST, validate, and format — each 30-50 lines. It also generated Jest tests for each.
7. Migrate to Modern Syntax
Prompt: "Migrate src/legacy/*.js from CommonJS to ES modules (import/export). Update package.json type field, change require to import, and fix any circular dependencies."
Usage Example: Claude converted 15 files, handled circular dependencies by extracting shared interfaces, and updated tsconfig.json for moduleResolution: "bundler".
8. Reduce Cyclomatic Complexity
Prompt: "Refactor src/validation/rules.ts — reduce cyclomatic complexity from 45 to under 10. Extract nested conditionals into lookup tables or strategy pattern."
Usage Example: Claude replaced a chain of if/else with a map of validation rules, reducing complexity to 8 and improving readability.
9. Async/Await Conversion
Prompt: "Convert all .then() chains in src/api/users.ts to async/await. Ensure error handling is preserved and no promise rejections are silent."
Usage Example: Claude transformed 5 callback-heavy endpoints to async/await, adding try-catch and logging for each.
10. Remove Dead Code
Prompt: "Analyze src/utils/*.ts for unused functions, exports, and variables. Use TypeScript compiler options noUnusedLocals and noUnusedParameters. Remove dead code and update imports."
Usage Example: Claude removed 4 unused utility functions and updated 3 files that still imported them.
Architecture Prompts
11. Microservices Decomposition
Prompt: "Given the monolith in src/monolith/, suggest a microservices split. Identify bounded contexts (auth, billing, notifications) and propose API contracts (gRPC or REST). Create a directory structure for each service."
Usage Example: Claude analyzed imports and dependencies, proposed 4 services, and generated a docker-compose.yml with inter-service communication via gRPC.
12. Database Schema Design
Prompt: "Design a PostgreSQL schema for a multi-tenant SaaS platform. Include users, organizations, roles, and audit logs. Use UUIDs, soft deletes, and row-level security (RLS). Provide migration SQL."
Usage Example: Claude created 6 tables with RLS policies, composite indexes, and a migration script using knex.
13. API Design Review
Prompt: "Review openapi.yaml for RESTful best practices. Check URL naming, HTTP methods, status codes, pagination, and rate limiting. Suggest improvements."
Usage Example: Claude flagged inconsistent pluralization (/user vs /users), missing 404 responses, and suggested cursor-based pagination for high-volume endpoints.
14. State Management Pattern
Prompt: "For a React app with 20+ components sharing state, recommend a state management pattern (Context API vs Redux vs Zustand). Show a minimal implementation with async actions."
Usage Example: Claude analyzed component tree and prop drilling, recommended Zustand for simplicity, and created a store with async thunks.
15. Caching Strategy
Prompt: "Design a caching layer for src/api/products.ts. Use Redis with TTL of 5 minutes for GET endpoints, and cache invalidation on PUT/PATCH. Show code for cache-aside pattern."
Usage Example: Claude implemented a cache-aside wrapper for Express routes, reducing database load by 70% in load tests.
Testing Prompts
16. Generate Unit Tests
Prompt: "Generate Jest unit tests for src/services/order.ts. Cover all branches, edge cases (empty cart, invalid coupon, payment failure), and mock external API calls (Stripe, email). Achieve 90% line coverage."
Usage Example: Claude created 12 test cases, including mocking Stripe responses with jest.mock, and coverage reached 92%.
17. Integration Test Setup
Prompt: "Create integration tests for the /api/orders endpoint using Supertest. Set up a test database with fixtures (PostgreSQL + testcontainers). Test CRUD operations and auth middleware."
Usage Example: Claude generated a testcontainers setup for PostgreSQL, seed data, and 8 integration tests that run in CI.
18. Property-Based Testing
Prompt: "Add property-based tests for src/utils/validation.ts using fast-check. Test that any valid email string passes, and any invalid email fails. Include edge cases like Unicode domains."
Usage Example: Claude wrote 3 property tests that generated 1000 random emails each, catching a bug with internationalized domain names.
19. Snapshot Testing
Prompt: "Add snapshot tests for all components in src/components/ui/. Use React Testing Library. Update snapshots if UI changes intentionally."
Usage Example: Claude created snapshots for 10 UI components, and later helped update them after a design system change.
20. Contract Testing
Prompt: "Write Pact contract tests for the user-service API. Verify that provider returns correct responses for consumer expectations. Include error cases (404, 500)."
Usage Example: Claude set up a Pact test suite with 5 consumer expectations and a provider verification script.
Documentation Prompts
21. README Generation
Prompt: "Generate a README.md for this project. Include: project description, setup instructions (install, run, test), API endpoints table, environment variables, and deployment guide."
Usage Example: Claude analyzed package.json, Dockerfile, and src/ to auto-generate a comprehensive README with badges.
22. Inline Documentation
Prompt: "Add JSDoc comments to all exported functions in src/services/. Include @param, @returns, @throws, and a brief description. Use TypeScript types."
Usage Example: Claude added 40+ JSDoc blocks, improving IDE intellisense and reducing onboarding time for new devs.
23. API Documentation
Prompt: "Generate OpenAPI 3.0 spec for the Express routes in src/routes/*.ts. Use swagger-jsdoc. Include request/response schemas and example values."
Usage Example: Claude created an openapi.yaml with 15 endpoints, validated it with swagger-cli, and integrated with Swagger UI.
24. Changelog Generation
Prompt: "Based on git log since last tag (v1.2.0), generate a CHANGELOG.md following Keep a Changelog format. Group by Added, Changed, Deprecated, Removed, Fixed, Security."
Usage Example: Claude parsed 47 commits, categorized them, and produced a clean changelog for the release.
25. Architecture Decision Records (ADR)
Prompt: "Create ADRs for key architectural decisions: microservices split, database choice (PostgreSQL vs MongoDB), and state management (Zustand). Follow ADR template: title, context, decision, consequences."
Usage Example: Claude generated 3 ADRs with rationale, alternatives considered, and trade-offs.
Advanced / Meta Prompts
26. Multi-File Refactoring
Prompt: "Refactor src/ directory structure from flat to feature-based. Move files into features/auth/, features/payments/, etc. Update all imports across the project."
Usage Example: Claude restructured 30 files, updated imports, and ran TypeScript compiler to verify no broken references.
27. Cross-Cutting Concerns
Prompt: "Add request logging middleware to all Express routes. Use correlation IDs (UUID per request), log method, URL, status code, and duration. Store logs in structured JSON."
Usage Example: Claude created a middleware, injected it into the app, and updated the logger to output JSON for ELK stack ingestion.
28. Migration Script
Prompt: "Write a migration script to rename created_at to createdAt in all PostgreSQL tables. Use knex migrations. Handle foreign key constraints."
Usage Example: Claude generated a migration that safely renamed columns, updated indexes, and rolled back on failure.
29. Codebase Health Check
Prompt: "Run a full health check on this codebase: lint, type-check, test coverage, outdated deps, and security audit. Output a summary with action items."
Usage Example: Claude chained eslint, tsc, jest --coverage, npm outdated, and npm audit — then produced a report with 5 action items.
30. Custom Script Generation
Prompt: "Write a bash script to automate deployment: build Docker image, tag with git commit hash, push to registry, and deploy to Kubernetes using kubectl set image."
Usage Example: Claude created a deploy.sh script with error handling and dry-run mode.
Conclusion
These 30 prompts cover the most common tasks I face daily — from quick security audits to full architectural redesigns. The key is specificity: tell Claude what files to look at, what standards to follow, and what output format you expect. With practice, you'll develop your own library of prompts tailored to your stack and workflow.
Remember that Claude Code is a tool, not a replacement for human judgment. Always review generated code, especially for security-critical changes. Use these prompts as a starting point, and iterate based on your project's needs. Happy coding!
If you use specific APIs in your projects, consider integrating them with ASI Biont to automate data flows. ASI Biont supports connecting to services like Stripe, Salesforce, and many others through its API — learn more at asibiont.com/courses.
Comments