Codex CLI Prompt Examples (2026) — 50+ Real-World Use Cases
The difference between a mediocre and a powerful Codex CLI workflow comes down to prompt quality. Below are 50+ battle-tested prompt templates organized by task type — copy, adapt, and run.
The three-part prompt formula: Scope (which files) + Constraint (what not to break) + Format (diff / direct edit / write file). Example: "Refactor the JWT validation in src/auth.ts → extract to validateJwt() → do not change the public interface."
1. Code Refactoring
Extract Duplicate Logic
$ codex "src/utils/validation.ts has 3 copies of email format validation logic — extract to a validateEmail() function, don't change callers' interfaces"
Split Large Functions
$ codex "processOrder() is over 200 lines — split into single-responsibility sub-functions following SRP, preserve existing behavior"
Replace Legacy API
$ codex "Replace all axios usage in src/ with the native fetch API, remove the axios dependency, keep TypeScript types correct"
Eliminate Magic Strings
$ codex "Replace all hardcoded HTTP status codes (200, 404, 500, etc.) in src/ with an HttpStatusCode enum, create src/constants/http.ts"
Unify Error Handling
$ codex "Audit all catch blocks in src/api/, replace console.error with logger.error, ensure the full error object is passed through"
Convert to Async/Await
$ codex "Rewrite all Promise.then() chains in src/services/user.js as async/await, preserve logic exactly"
Type Safety Improvement
$ codex "Add concrete TypeScript types to all 'any' types in src/api/client.ts — infer from function signatures and usage, no 'as' casts"
Modular Split
$ codex "src/store/index.ts is 500+ lines — split into feature modules (user, cart, orders), keep exports backward-compatible"
2. Test Generation
Unit Tests
$ codex "Generate Jest unit tests for every exported function in src/utils/date.ts, covering normal inputs, edge cases, and error paths"
Fill Coverage Gaps
$ codex "Run npx jest --coverage, find files below 80% coverage, add missing test cases to bring them up"
Integration Tests
$ codex "Generate supertest integration tests for the /api/users route, covering GET/POST/PUT/DELETE, including auth and permission checks"
E2E Tests (Playwright)
$ codex "Write a Playwright E2E test for the login flow: navigate to /login → fill email and password → click submit → assert redirect to /dashboard"
Test Data Factories
$ codex "Create a user factory function using faker.js for registration tests, support traits (admin, premium, banned)"
Fix Failing Tests
$ codex "Run npm test, find all failing test cases, diagnose root cause, fix the bug in either the test or implementation (only fix the wrong side)"
Snapshot Tests
$ codex "Generate React Testing Library snapshot tests for src/components/Button.tsx, covering all variants (primary, secondary, danger)"
3. Bug Fixing & Debugging
Analyze Stack Traces
$ codex "Analyze this error: TypeError: Cannot read property 'id' of undefined at UserCard.tsx:42 — find the root cause and fix it"
Fix TypeScript Errors
$ codex "Run npx tsc --noEmit and fix all TypeScript errors — no 'any' or 'as' casts as workarounds"
Fix Memory Leaks
$ codex "Check all useEffect hooks in src/hooks/ for uncleaned subscriptions, timers, or event listeners — fix any leaks"
Fix Race Conditions
$ codex "src/api/search.ts has a race condition where old responses overwrite newer ones — fix using AbortController"
Fix SQL Injection
$ codex "Audit all database queries in src/db/queries.ts — replace string concatenation with parameterized queries to prevent SQL injection"
Performance Profiling
$ codex "Analyze why ProfilePage re-renders excessively (React Profiler log in debug.log) — fix with useMemo and useCallback where appropriate"
4. Documentation
JSDoc Comments
$ codex "Add complete JSDoc comments to all exported functions in src/utils/ — include @param, @returns, @throws, and a usage example for each"
README Generation
$ codex "Generate a complete README.md from the project structure and package.json — include overview, install, usage examples, API docs, contributing guide"
OpenAPI Spec
$ codex "Analyze all Express routes in src/routes/ and generate an OpenAPI 3.0 spec (YAML), including request/response schemas and examples"
CHANGELOG Generation
$ codex "Parse 'git log --oneline' for the last 50 commits, organize into a v2.0.0 CHANGELOG.md entry following Conventional Commits format"
Inline Comments
$ codex "Add inline comments to src/algorithms/dijkstra.ts explaining each key step — target audience: developers unfamiliar with graph algorithms"
5. Code Review & Security
Security Audit
$ codex "Audit src/auth/: check JWT validation completeness, password hashing algorithm strength, CORS config, and whether secrets leak into logs"
Dependency Vulnerabilities
$ codex "Run npm audit, upgrade each high/critical vulnerability to a safe version, run tests to confirm nothing breaks"
Complexity Analysis
$ codex "Use eslint-plugin-complexity to find functions with cyclomatic complexity > 10, provide refactoring suggestions to simplify them"
Secret Scanning
$ codex "Scan the entire codebase for hardcoded API keys, passwords, tokens — replace with environment variables, update .env.example"
Code Style Enforcement
$ codex "Fix all ESLint and Prettier violations in src/ per .eslintrc.json and .prettierrc — ensure CI checks pass"
6. Database & Migrations
Generate Migration
$ codex "Add a lastLoginAt field (TIMESTAMP, nullable) to the User model — generate a Prisma migration file including rollback script"
Fix N+1 Queries
$ codex "Analyze src/db/userQueries.ts for N+1 query patterns — optimize with JOIN or DataLoader batch loading"
Schema Documentation
$ codex "Read prisma/schema.prisma and generate a human-readable database design doc (Markdown) including ER diagram description and field explanations"
Seed Data
$ codex "Create prisma/seed.ts with dev environment seed data: 10 users (1 admin), 20 products, 50 orders"
Data Migration Script
$ codex "Write a Node.js script to migrate MongoDB 'users' collection to PostgreSQL 'users' table — handle type coercion, nulls, batch insert 100 rows at a time"
7. CI/CD & Automation
GitHub Actions CI
$ codex "Generate a GitHub Actions CI workflow for this Node.js project: Node 18/20 matrix, lint, build, test, coverage upload to Codecov"
Automated Release
$ codex "Create a GitHub Actions release workflow: on tag push, run tests → build → publish to npm → generate GitHub Release with CHANGELOG"
Dockerize
$ codex "Write a multi-stage Dockerfile for this Express app (Node 18 Alpine), add docker-compose.yml with PostgreSQL and Redis, include health checks"
Batch Code Update
$ codex exec "Replace all 'var' keywords in .js files with 'const' or 'let' based on reassignment — skip node_modules"
Auto Quality Fix
$ codex exec --approval-mode full-auto "Run eslint --fix and prettier --write, then run tests — if tests fail, roll back all changes"
8. Framework-Specific Examples
React Refactor — Class to Function
$ codex "Convert src/components/UserList.tsx from class to function component with Hooks — add TypeScript types, keep the props interface identical"
Next.js API Route
$ codex "Implement pages/api/users/[id].ts as a full REST API (GET/PUT/DELETE) with auth middleware, zod input validation, and error handling"
Python / pytest
$ codex "Generate pytest tests for app/services/order_service.py using unittest.mock for DB calls — cover all business logic branches"
Go Interface Implementation
$ codex "Implement the Storage interface defined in internal/storage/interface.go using PostgreSQL (pgx/v5), include connection pooling and error handling"
Django REST Framework ViewSet
$ codex "Create a DRF ViewSet for the Django User model with custom permissions (users can only modify their own data), filtering, search, and pagination"
Want to learn more about prompt engineering? See the Tips & Advanced Usage guide. Need to run these in CI/CD pipelines? See CI/CD Automation and the codex exec Guide.
🔍 Language-specific tutorials:
Python Developer Guide (pytest, mypy, Django/FastAPI) ·
JavaScript/TypeScript Guide (React, Next.js, Node.js)