The Best OpenAI Codex Prompts for Building a SaaS MVP
OpenAI Codex is an AI coding agent that works in your terminal, IDE (VSCode, Cursor, Windsurf), and the cloud. It uses the latest OpenAI models including GPT-5, o3, and GPT-4o to autonomously navigate your codebase, edit files, run commands, and build complete features. This prompt library gives you production-ready examples optimized for Codex's autonomous capabilities.
Why These Prompts Work with Codex
Prompts are designed for Codex's ability to navigate codebases, edit multiple files, run commands, and execute tests autonomously.
Each prompt breaks down complex features into clear steps that Codex can work through methodically, showing progress along the way.
Optimized for GPT-5's advanced reasoning and o3's deep planning capabilities. Uses extended thinking for architectural decisions.
Explicit instructions ensure authentication checks, input validation, and modern Next.js 15 patterns are followed in every implementation.
Step 1: System Context (Optional)
While Codex can infer your stack from your codebase, providing explicit context ensures consistency. Include this in your first message or save it as a project-specific instruction file.
You are an expert Full-Stack SaaS Developer specializing in production-ready MVPs.
## Tech Stack
- **Frontend**: Next.js 15 (App Router), React, TypeScript (strict mode)
- **Styling**: Tailwind CSS + Shadcn UI components
- **Database**: Supabase (PostgreSQL) with Drizzle ORM
- **Auth**: Kinde Auth
- **Payments**: Stripe (subscriptions)
- **Email**: Resend + @react-email/components
- **Deployment**: Vercel
## Project Structure
```
app/
├── actions/ # Server actions for mutations
├── api/ # API routes (Stripe webhooks, etc.)
├── dashboard/ # Main app dashboard
└── [route]/page.tsx # Pages
components/ # React components
db/
├── schema.ts # Drizzle schema
└── index.ts # Database connection
emails/ # Email templates
lib/ # Utility functions
```
## Code Standards
### TypeScript
- Always use strict mode
- No 'any' types - use proper type annotations
- Functional components with hooks
- Interface over type for object shapes
### React/Next.js
- **Server components by default** - only use "use client" when needed:
- Using state (useState, useReducer)
- Using effects (useEffect, useLayoutEffect)
- Event handlers (onClick, onChange, etc.)
- Browser-only APIs
- Server Actions in `app/actions/` for all mutations
- Call `revalidatePath()` after mutations
- Proper loading states and error handling
### Database (Drizzle ORM)
- snake_case for database columns
- camelCase for TypeScript field names
- Always filter queries by `userId` for security
- Use transactions for multi-step operations
- Include proper foreign keys and indexes
- Generate SQL for Supabase (don't use drizzle-kit push)
### Security
- **CRITICAL**: Every server action MUST check authentication:
```typescript
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
export async function myServerAction() {
const { getUser } = getKindeServerSession();
const user = await getUser();
if (!user) {
throw new Error("Unauthorized");
}
// Filter by userId
const data = await db.select()
.from(table)
.where(eq(table.userId, user.id));
}
```
- Validate all inputs with Zod
- Never expose secrets in client code
- Use environment variables for API keys
- Verify Stripe webhook signatures
### UI/UX
- Mobile-first responsive design
- Use Shadcn UI components (Dialog, Card, Button, Input, Textarea, Badge, Tabs, etc.)
- Loading states for all async operations
- Error boundaries and helpful error messages
- Toast notifications for user feedback
- Professional look (like Stripe or Linear)
### File Naming
- Components: PascalCase (`UserProfile.tsx`)
- Routes: kebab-case (`user-profile/page.tsx`)
- Actions: camelCase (`createPost.ts`)
- Constants: UPPER_SNAKE_CASE
## Development Workflow
1. **Understand**: Analyze requirements thoroughly
2. **Plan**: Design architecture and database schema
3. **Implement**: Build features with proper security
4. **Test**: Verify functionality and edge cases
5. **Refine**: Optimize performance and code quality
## Best Practices
- Keep components under 200 lines
- One feature per file
- CRUD operations in server actions only
- Always review AI-generated code before committing
- Test on mobile and desktop
- Use TypeScript's type system to catch errors early
- Prefer composition over complex prop drilling
- Handle loading and error states consistently💡 Getting Started with Codex
- 1. Install Codex CLI:
npm i -g @openai/codex - 2. Start Codex:
codexin your project directory - 3. Or use IDE extension: Install the Codex extension for VSCode, Cursor, or Windsurf
- 4. Choose your model: Select GPT-5 for advanced reasoning or o3 for deep planning tasks
Step 2: Architecture Planning (o3 recommended)
Use this prompt with o3 or GPT-5 for deep architectural planning. The model will use extended reasoning to design your database schema, component hierarchy, and implementation roadmap before any code is written.
I want to build a SaaS MVP called [PRODUCT_NAME]. ## Product Overview **What it does**: [BRIEF_DESCRIPTION] **Core problem it solves**: [MAIN_PAIN_POINT] **Target users**: [WHO_USES_IT] **Key features**: 1. [FEATURE_1] 2. [FEATURE_2] 3. [FEATURE_3] ## Your Task: Deep Architecture Planning Use your reasoning capabilities to analyze this product and create a comprehensive architecture plan. Take time to think through the technical challenges and optimal solutions. ### Phase 1: Requirements Analysis 1. **Problem breakdown**: What are the core technical challenges? 2. **User flows**: Map out the critical user journeys 3. **Data relationships**: How does information flow through the system? 4. **Edge cases**: What could go wrong? How do we handle it? ### Phase 2: Database Schema Design Design the complete database schema using Drizzle ORM: **Standard tables**: - `users`: id (varchar 255, Kinde user ID), email, firstName, lastName, role, createdAt, stripeCustomerId, stripeSubscriptionId, subscriptionStatus, subscriptionEndsAt **Custom tables** (2-4 tables for core features): - What entities does [PRODUCT_NAME] need to store? - What are the relationships between them? - What fields are required vs optional? - What indexes are needed for performance? **Requirements**: - Use snake_case for database columns - camelCase for TypeScript field names - Foreign keys to users.id with proper cascade rules - Indexes on frequently queried fields - Consider data volume and query patterns Provide the complete Drizzle schema definition in `db/schema.ts` format. ### Phase 3: API & Server Actions Structure Plan the server actions needed: For each core feature, what operations are needed? - Create operations (what data needs validation?) - Read operations (what filters and sorting?) - Update operations (what can be modified?) - Delete operations (what cascade rules?) What security checks are required for each action? ### Phase 4: Component Architecture Design the React component hierarchy: **Dashboard structure**: - What stats/metrics should users see? - How to organize different features? - What's the information hierarchy? **Feature components** (for each core feature): - What forms are needed? - How to display lists of items? - What actions can users take? - How to handle empty states? **Shared components**: - What UI patterns repeat across features? - What shadcn components to use? ### Phase 5: Subscription & Monetization Design the subscription model: **Free tier**: - What limits make sense? (e.g., 5 items max, 10 API calls/day) - How to enforce these limits? - What value do free users get? **Plus tier** ($49/year): - What becomes unlimited? - What exclusive features? - How to handle upgrade/downgrade flows? ### Phase 6: Implementation Roadmap Provide a step-by-step build sequence: 1. Step name → Files to create → Key considerations 2. Step name → Files to create → Key considerations ... **DO NOT write the actual code yet.** I need: 1. Your architectural reasoning and analysis 2. Complete Drizzle schema with explanations 3. List of all server actions needed 4. Component hierarchy diagram 5. Subscription logic plan 6. Step-by-step implementation roadmap Take your time to reason through this carefully. Think about scalability, security, and user experience.
When to Use This Prompt
This prompt is perfect for the initial planning phase. Use it to:
- • Design your database schema before implementation
- • Identify technical challenges and solutions
- • Plan component architecture and state management
- • Get a clear roadmap before Codex starts building
Step 3: Complete SaaS MVP Builder
This comprehensive prompt walks Codex through building your entire SaaS autonomously. Codex will navigate your codebase, create files, edit code, run tests, and build your complete MVP step-by-step. Use GPT-5 or GPT-4o for implementation.
I need you to build a complete, production-ready SaaS MVP called [PRODUCT_NAME].
## Product Details
**What it does**: [BRIEF_DESCRIPTION]
**Core problem it solves**: [MAIN_PAIN_POINT]
**Target users**: [WHO_USES_IT]
**Key features**: [LIST_2_4_CORE_FEATURES]
## Build Instructions
Work through each step autonomously. Use your file navigation, editing, and command execution capabilities. After each major step, summarize what you've done and ask if you should proceed.
---
### Step 1: Database Schema Design
**Explore**: Read the existing `db/schema.ts` file to understand the current schema pattern.
**Design & Implement**:
- Update `db/schema.ts` with:
- Standard users table (id varchar 255, email, firstName, lastName, role, createdAt, stripeCustomerId, stripeSubscriptionId, subscriptionStatus, subscriptionEndsAt)
- 2-4 custom tables for [PRODUCT_NAME]'s core features
- snake_case columns, camelCase TypeScript
- Foreign keys to users.id
- Indexes on frequently queried fields
**Generate SQL**:
- Create migration SQL file I can run in Supabase
- Don't use drizzle-kit push
**Verify**: Show me the schema and explain your design decisions.
---
### Step 2: Theme & Branding
**Explore**: Read `app/globals.css` and `components/LandingPageClient.tsx` to understand current styling.
**Customize**:
- Choose 2 Google Fonts that match [PRODUCT_NAME] personality
- Update `app/globals.css`:
- Add @import for fonts at the very top (before @tailwind)
- Update CSS variables for primary, secondary, accent colors
- Update `components/LandingPageClient.tsx`:
- New hero headline for [PRODUCT_NAME]
- Update feature card copy
- Add relevant Lucide React icons
**Verify**: Show me the color scheme and copy.
---
### Step 3: Server Actions for Core Features
For each core feature of [PRODUCT_NAME]:
**Create `app/actions/[feature].ts`**:
- create[Feature], get[Features], update[Feature], delete[Feature]
- **CRITICAL**: Every function must:
- Import and check auth with getKindeServerSession
- Validate inputs with Zod
- Filter ALL queries by userId
- Call revalidatePath after mutations
- Include proper error handling
**Example structure**:
```typescript
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import { db } from "@/db";
import { z } from "zod";
export async function create[Feature](data) {
const { getUser } = getKindeServerSession();
const user = await getUser();
if (!user) throw new Error("Unauthorized");
// Validation, database ops, revalidatePath
}
```
**Test**: Run the actions to verify they work.
---
### Step 4: React Components
For each core feature, create:
**1. `components/Create[Feature]Dialog.tsx`**:
- Use shadcn Dialog, Input, Textarea, Button
- "use client" directive
- Loading states and error handling
- Call server actions
**2. `components/[Feature]List.tsx`**:
- Display items in Cards
- Edit/delete actions
- Empty state for new users
- "use client" directive
**3. `components/[Feature]Stats.tsx`**:
- Summary metrics
- Use shadcn Card
**Design**: Mobile responsive, professional UI (like Stripe or Linear)
---
### Step 5: Dashboard Integration
**Update `app/dashboard/page.tsx`**:
- Import all feature components
- Show stats overview at top
- Onboarding flow for users with no data
- Use shadcn Tabs for different feature sections
- Clean, organized layout
**Test**: Visit /dashboard and verify everything renders correctly.
---
### Step 6: Subscription Plans
**Create `lib/subscription.ts`**:
- isPlusUser(user) helper
- canAccess[Feature](user) helpers
- Free plan limits: [DEFINE_LIMITS]
- Plus plan: $49/year, unlimited
**Create `components/UpgradePrompt.tsx`**:
- Dialog explaining Plus benefits
- Stripe checkout CTA
**Create `app/pricing/page.tsx`**:
- Pricing comparison table
- Feature comparison
- Checkout button
**Enforce limits**:
- Update server actions to check subscription status
- Return errors when free users hit limits
- Show UpgradePrompt when limits reached
---
### Step 7: Stripe Integration
**Create `app/api/create-checkout-session/route.ts`**:
- Create Stripe checkout session for $49/year
- Return checkout URL
**Create `app/api/webhooks/stripe/route.ts`**:
- Verify webhook signature (CRITICAL for security)
- Handle events:
- checkout.session.completed → upgrade user to Plus
- customer.subscription.updated → handle renewals
- customer.subscription.deleted → downgrade to Free
- Update user in database
**Link checkout**: Connect pricing page to checkout API
**Test**: Use Stripe test card 4242 4242 4242 4242
---
### Step 8: Email Templates
**Create `emails/WelcomeEmail.tsx`**:
- Use @react-email/components
- Welcome message for new users
**Create `emails/SubscriptionConfirmation.tsx`**:
- Thank you for upgrading to Plus
**Create `lib/email.ts`**:
- sendWelcomeEmail(user) using Resend
- sendSubscriptionConfirmation(user) using Resend
**Trigger emails**:
- Welcome email in auth callback
- Subscription email in Stripe webhook
---
### Step 9: Production Preparation
**Run build**:
- Execute `npm run build`
- Fix ALL TypeScript errors
- Fix ALL ESLint warnings
**Verify**:
- Create `.env.example` with all required variables
- No hardcoded secrets anywhere
- Add comments to complex code
- All imports work correctly
---
### Step 10: Final Testing & Polish
**Complete testing**:
- Sign up new user → verify onboarding
- Create/edit/delete items → test CRUD
- Hit free plan limit → see upgrade prompt
- Checkout with test card → become Plus user
- Verify unlimited access as Plus user
- Test on mobile and desktop
- Verify emails are sent
**Success criteria checklist**:
- ✅ All CRUD operations work
- ✅ Authentication flow complete
- ✅ Stripe checkout functional
- ✅ Free users hit limits correctly
- ✅ Plus users have unlimited access
- ✅ Emails trigger properly
- ✅ Mobile and desktop responsive
- ✅ Zero TypeScript errors
- ✅ `npm run build` succeeds
- ✅ Ready to deploy to Vercel
---
## Your Approach
Use your autonomous capabilities:
- Navigate the codebase to find relevant files
- Read existing code to understand patterns
- Edit multiple files to implement features
- Run commands to test and verify
- Fix errors as they appear
After each step, show me:
1. What you created/modified
2. Key design decisions you made
3. Any challenges or considerations
4. Whether you're ready to proceed to the next step
Work methodically and thoroughly. Don't skip steps or rush. This is a production application that real users will depend on.🚀 How to Use This Prompt with Codex
- 1. Start Codex in your project:
codex - 2. Paste this prompt with your product details filled in
- 3. Let Codex work autonomously - it will navigate files, make edits, and run commands
- 4. Review progress after each step
- 5. Approve or provide feedback before Codex continues
- 6. Deploy when all 10 steps are complete
Specialized Prompts for Common Tasks
Use these targeted prompts for specific development tasks. Each one is designed for Codex to work autonomously on a focused objective.
Build a complete [FEATURE_NAME] feature for my SaaS. ## Feature Description **What it does**: [DESCRIPTION] **User flow**: [DESCRIBE_USER_ACTIONS] **Data needed**: [WHAT_DATA_TO_STORE] ## Implementation Navigate the codebase and create all necessary files: ### 1. Database Schema **Update `db/schema.ts`**: - Add new table for [FEATURE_NAME] - Include fields: [LIST_FIELDS] - Foreign key to users.id - Proper indexes - Generate migration SQL ### 2. Server Actions **Create `app/actions/[feature].ts`**: - create[Feature](data) - with Zod validation - get[Features](userId) - filtered by user - update[Feature](id, data) - with auth check - delete[Feature](id) - with auth check - All functions call revalidatePath after mutations ### 3. React Components **Create `components/Create[Feature]Dialog.tsx`**: - Dialog form with shadcn UI - Loading and error states - Calls create action **Create `components/[Feature]List.tsx`**: - Display all items in Cards - Edit/delete buttons - Empty state - Mobile responsive **Create `components/[Feature]Stats.tsx`**: - Summary metrics - Use shadcn Card components ### 4. Dashboard Integration **Update `app/dashboard/page.tsx`**: - Import new components - Add to dashboard layout - Maintain clean organization ### 5. Testing - Run the app and verify CRUD works - Test on mobile and desktop - Check auth filtering works - Fix any TypeScript errors Show me each file as you create it and explain your implementation decisions.
Design the database schema for my SaaS: [PRODUCT_NAME]. ## Product Overview **What it does**: [BRIEF_DESCRIPTION] **Core features**: [LIST_2_4_FEATURES] ## Your Task Analyze the product and design a complete database schema using Drizzle ORM. ### Schema Design **Standard tables**: - `users`: id (varchar 255, Kinde ID), email, firstName, lastName, role, createdAt, stripeCustomerId, stripeSubscriptionId, subscriptionStatus, subscriptionEndsAt **Custom tables** (2-4 for core features): - Determine what entities need to be stored - Define relationships between entities - Choose appropriate data types - Add indexes for performance - Use snake_case for columns, camelCase for TypeScript ### Deliverables 1. **Complete `db/schema.ts` file** with all tables 2. **SQL migration file** I can run in Supabase 3. **Explanation** of your design decisions: - Why these tables? - What relationships? - What indexes and why? - What constraints? ### Requirements - Foreign keys with proper cascade rules - Indexes on frequently queried fields - Nullable vs required fields thought through - Consider data volume and query patterns - Follow Drizzle ORM best practices Show me the complete schema code and SQL, then explain your reasoning.
Set up Stripe subscription payments for my SaaS.
## Subscription Plans
**Free tier**: [DEFINE_LIMITS - e.g., 5 items max, 10 API calls/day]
**Plus tier**: $49/year, unlimited access
## Implementation
### 1. Subscription Logic
**Create `lib/subscription.ts`**:
- isPlusUser(user): boolean
- isFreePlan(user): boolean
- canCreate[Feature](user, currentCount): boolean
- Plan limit constants
### 2. UI Components
**Create `components/UpgradePrompt.tsx`**:
- Dialog explaining Plus benefits
- Comparison of Free vs Plus
- "Upgrade to Plus" CTA button
**Create `app/pricing/page.tsx`**:
- Pricing comparison table
- Feature comparison list
- Checkout button that calls API
### 3. Checkout API
**Create `app/api/create-checkout-session/route.ts`**:
- Get current user with Kinde
- Create Stripe checkout session for $49/year
- Set success/cancel URLs
- Return checkout URL
### 4. Webhook Handler
**Create `app/api/webhooks/stripe/route.ts`**:
- **CRITICAL**: Verify webhook signature
- Handle `checkout.session.completed`:
- Update user to Plus plan
- Set subscriptionStatus, stripeCustomerId, stripeSubscriptionId
- Send confirmation email
- Handle `customer.subscription.updated`:
- Update subscription end date
- Handle plan changes
- Handle `customer.subscription.deleted`:
- Downgrade user to Free
- Send notification email
### 5. Enforce Limits
**Update server actions**:
- Check subscription before create operations
- Return error if free user hits limit
- Include subscription info in responses
Example:
```typescript
export async function createItem(data) {
const user = await getUser();
if (!user) throw new Error("Unauthorized");
const currentCount = await db.select().from(items)
.where(eq(items.userId, user.id));
if (!isPlusUser(user) && currentCount.length >= 5) {
throw new Error("Free plan limit reached. Upgrade to Plus for unlimited items.");
}
// Create item...
}
```
### 6. Testing
- Test checkout flow with card: 4242 4242 4242 4242
- Verify webhook events are received
- Test limit enforcement for free users
- Verify Plus users have unlimited access
Work through each file and show me your implementation.Prepare my SaaS for production deployment to Vercel. ## Pre-Deployment Checklist Navigate the codebase and complete each task: ### 1. Fix Build Errors - Run `npm run build` - Fix ALL TypeScript errors - Fix ALL ESLint warnings - Don't proceed until build succeeds ### 2. Environment Variables **Create `.env.example`**: - List all required environment variables (without values) - Add comments explaining what each is for - Organize by service (Database, Auth, Stripe, Email, etc.) Example: ``` # Database DATABASE_URL= DIRECT_DATABASE_URL= # Kinde Auth KINDE_CLIENT_ID= KINDE_CLIENT_SECRET= ... ``` ### 3. Security Review **Check all server actions**: - Every action has authentication check - All queries filtered by userId - Input validation with Zod - No hardcoded secrets **Check API routes**: - Stripe webhooks verify signatures - Proper error handling - No secrets exposed ### 4. Code Quality - Remove console.logs from production code - Add comments to complex logic - Remove unused imports - Remove commented-out code - Consistent formatting ### 5. Documentation **Update README.md**: - Setup instructions - Required environment variables - Development commands - Deployment steps - Tech stack overview ### 6. Testing **Manual testing checklist**: - [ ] User can sign up - [ ] User can log in - [ ] Dashboard loads correctly - [ ] Can create items - [ ] Can edit items - [ ] Can delete items - [ ] Free tier limits work - [ ] Stripe checkout works (test mode) - [ ] Emails are sent - [ ] Mobile responsive - [ ] No console errors ### 7. Deployment Checklist Create a deployment checklist in the README: - [ ] Set environment variables in Vercel - [ ] Run database migrations in production - [ ] Update Kinde callback URLs - [ ] Configure Stripe webhook endpoint - [ ] Test in production - [ ] Monitor for errors Work through each step and show me what you've fixed/created.
Review this codebase for security, performance, and quality issues. ## Review Areas Navigate the codebase and perform a comprehensive review: ### 1. Security Audit **Server Actions** (`app/actions/**`): - [ ] Every action checks authentication - [ ] All queries filtered by userId - [ ] Input validation with Zod - [ ] Proper error messages (no sensitive data) **API Routes** (`app/api/**`): - [ ] Webhook signature verification - [ ] Authentication checks where needed - [ ] No exposed secrets **Database Queries**: - [ ] No raw SQL without sanitization - [ ] Proper parameterization - [ ] Transaction handling for multi-step ops ### 2. Performance Review **Database**: - [ ] Indexes on frequently queried fields - [ ] N+1 query problems - [ ] Efficient query patterns **React Components**: - [ ] Unnecessary re-renders - [ ] Large component trees - [ ] Missing React.memo where beneficial - [ ] Proper key props in lists **Next.js**: - [ ] Server components used by default - [ ] Client components only when necessary - [ ] Proper loading states - [ ] Image optimization ### 3. Code Quality **TypeScript**: - [ ] No 'any' types - [ ] Proper type annotations - [ ] Interfaces for complex shapes - [ ] Strict mode enabled **React/Next.js**: - [ ] Consistent component patterns - [ ] Proper error boundaries - [ ] Loading states for async ops - [ ] revalidatePath after mutations **Code Organization**: - [ ] Files under 200 lines - [ ] Clear separation of concerns - [ ] Consistent naming - [ ] No code duplication ### 4. User Experience - [ ] Mobile responsiveness - [ ] Loading states - [ ] Error messages - [ ] Empty states - [ ] Success feedback ## Deliverables Provide: 1. **Critical issues** (security/data loss risks) 2. **High priority** (bugs, performance problems) 3. **Medium priority** (code quality, maintainability) 4. **Nice to have** (optimizations, polish) For each issue: - File and line number - Description of the problem - Why it matters - Suggested fix - Example code if applicable Be thorough but constructive. Focus on actionable improvements.
Pro Tips for Using Codex
- Let Codex work autonomously: Trust its ability to navigate files and make changes
- Review changes: Always review diffs before approving major changes
- Use specific prompts: These targeted prompts work better than generic requests
- Delegate to cloud: For long-running tasks, use Codex cloud to work in the background
- Integrate with GitHub: Set up Codex to auto-review PRs for your team
- Choose the right model: Use o3 for planning, GPT-5 for complex implementation, GPT-4o for speed
More AI Coding Tool Prompts
Prompts for Anthropic's CLI tool
View prompts →Prompts for the AI code editor
View prompts →Prompts for Gemini 3 & Google's platform
View prompts →