Transform SaaSPilot into the most AI-coding-agent-friendly SaaS boilerplate by adding comprehensive documentation, standardized patterns, and intelligent code organization that enables AI assistants (Claude, Cursor, GitHub Copilot, etc.) to quickly understand and modify the codebase.
- Create
/docsdirectory structure - Add AI instruction files
- Document architecture and patterns
- Create API documentation
- Add component relationship maps
- Add comprehensive JSDoc comments
- Implement standardized file headers
- Create pattern documentation
- Organize modular feature system
- Add prompt templates
- Create setup automation scripts
- Add example projects
- Create troubleshooting guides
- Add testing scaffolding
- Create migration guides
- Add dependency visualizations
- Implement code generation templates
Create the following new directories and files:
/saas-pilot-root/
├── /docs/
│ ├── ai-instructions.md
│ ├── architecture.md
│ ├── api-documentation.md
│ ├── coding-patterns.md
│ ├── component-map.md
│ ├── database-schema.md
│ ├── deployment-guide.md
│ └── troubleshooting.md
│
├── /prompts/
│ ├── add-new-feature.md
│ ├── create-api-endpoint.md
│ ├── add-payment-plan.md
│ ├── customize-ui-component.md
│ ├── modify-database-schema.md
│ └── integrate-third-party-service.md
│
├── /examples/
│ ├── /ai-newsletter-platform/
│ ├── /form-builder-saas/
│ ├── /waitlist-management/
│ ├── /course-platform/
│ └── /crm-lite/
│
├── /scripts/
│ ├── setup-ai-dev.sh
│ ├── generate-docs.js
│ └── validate-structure.js
│
└── CLAUDE.md (root level)
Create this file with the following content:
# AI Coding Agent Instructions for SaaSPilot
## 🤖 For AI Assistants
This document provides context and instructions for AI coding agents working with the SaaSPilot codebase.
### Quick Context
- **Framework**: Next.js 14+ (App Router)
- **Language**: TypeScript
- **Database**: MongoDB with Prisma ORM
- **Authentication**: NextAuth.js
- **Payments**: Stripe
- **UI**: Tailwind CSS + Shadcn/ui
- **Email**: Resend / SendGrid
### Project Structure Philosophy
- Feature-based organization in `/app` directory
- Shared components in `/components`
- Business logic in `/actions` (server actions)
- Database queries through Prisma in `/db`
- Type definitions in `/types`
### Key Conventions
#### 1. Naming Conventions
- Components: PascalCase (`UserDashboard.tsx`)
- Files: kebab-case for non-components (`user-service.ts`)
- API routes: kebab-case (`/api/user-profile/route.ts`)
- Database models: PascalCase (`User`, `Subscription`)
#### 2. File Structure Pattern
Every feature should follow this structure:/app/feature-name/ ├── page.tsx (main page) ├── layout.tsx (if needed) ├── loading.tsx (loading state) ├── error.tsx (error boundary) └── components/ (feature-specific components)
#### 3. Server Actions Pattern
Location: `/actions/feature-name/`
```typescript
'use server'
import { auth } from '@/auth'
import { db } from '@/db'
export async function actionName(data: ActionInput): Promise<ActionResult> {
// 1. Authentication check
const session = await auth()
if (!session?.user) {
return { error: 'Unauthorized' }
}
// 2. Validation
const validated = schema.parse(data)
// 3. Database operation
const result = await db.model.operation()
// 4. Return result
return { success: true, data: result }
}
Location: /app/api/resource-name/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
export async function GET(req: NextRequest) {
const session = await auth()
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
// Logic here
return NextResponse.json({ data })
}'use client' // Only if client-side features needed
import { ComponentProps } from '@/types'
interface Props {
// Props with JSDoc
}
/**
* @ai-context Brief description of component purpose
* @ai-dependencies List any external dependencies
* @ai-modify-safe Yes/No - whether AI can safely modify
*/
export function ComponentName({ prop1, prop2 }: Props) {
// Component logic
return (
// JSX
)
}import { db } from '@/db'
// ✅ Good
const user = await db.user.findUnique({ where: { id } })
// ❌ Avoid raw queries unless absolutely necessaryconst result = await db.$transaction(async (tx) => {
const user = await tx.user.create({ data: userData })
const profile = await tx.profile.create({ data: { userId: user.id } })
return { user, profile }
})Always verify authentication before protected operations:
import { auth } from '@/auth'
const session = await auth()
if (!session?.user?.id) {
// Handle unauthorized
}Access through process.env with fallbacks:
const apiKey = process.env.API_KEY
if (!apiKey) {
throw new Error('API_KEY is required')
}Use consistent error patterns:
try {
// Operation
} catch (error) {
console.error('Operation failed:', error)
return { error: 'User-friendly error message' }
}- Use Tailwind utility classes
- Follow Shadcn/ui component patterns
- Responsive design: mobile-first (sm, md, lg, xl breakpoints)
- Dark mode support: use
dark:prefix
import { describe, it, expect } from '@jest/globals'
describe('Feature Name', () => {
it('should perform expected behavior', async () => {
// Arrange
// Act
// Assert
})
})- Update
prisma/schema.prisma - Run
npx prisma generate - Create migration:
npx prisma migrate dev - Update TypeScript types if needed
- Create
/app/api/endpoint-name/route.ts - Implement HTTP methods (GET, POST, etc.)
- Add authentication checks
- Document in
/docs/api-documentation.md
- Create
/app/feature-name/page.tsx - Add server actions in
/actions/feature-name/ - Create components in feature directory
- Update navigation if needed
- Add credentials to
.env.example - Create service file in
/services/service-name.ts - Add initialization in appropriate location
- Document usage in
/docs/
- Any file in
/app(pages, layouts, components) - Any file in
/components - Server actions in
/actions - Services in
/services - Schemas in
/schemas - Styles in
/app/globals.css
/auth.tsand/auth.config.ts(authentication core)/middleware.ts(routing and protection)/prisma/schema.prisma(requires migration)- Environment variable handling
/package-lock.json(use package.json instead)- Generated files in
/node_modules .next/build directory
- Ask for clarification
- Suggest creating a new file rather than modifying core files
- Propose the change before implementing
- Add TODO comments for human review
# Development
npm run dev
# Database
npx prisma studio # Visual database editor
npx prisma generate # Generate Prisma client
npx prisma migrate dev # Create and apply migration
npx prisma db push # Push schema without migration
# Build
npm run build
npm run start
# Linting
npm run lint- Check
/docsdirectory for specific documentation - Review
/examplesfor implementation patterns - See
/promptsfor common task templates
---
## 📄 File 2: `/docs/architecture.md`
```markdown
# SaaSPilot Architecture
## System Overview
┌─────────────────────────────────────────────────────────────┐ │ CLIENT LAYER │ │ ┌─────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Landing │ │ Auth Pages │ │ Dashboard │ │ │ │ Pages │ │ (Login/Reg) │ │ Pages │ │ │ └─────────────┘ └──────────────┘ └──────────────┘ │ └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ │ NEXT.JS APP ROUTER │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ Middleware (Auth, i18n, Rate Limiting) │ │ │ └─────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ │ API/ACTIONS LAYER │ │ ┌───────────┐ ┌───────────┐ ┌────────────┐ │ │ │ Server │ │ API │ │ Webhooks │ │ │ │ Actions │ │ Routes │ │ (Stripe) │ │ │ └───────────┘ └───────────┘ └────────────┘ │ └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ │ SERVICE LAYER │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ Auth │ │ Payments │ │ Email │ │ Other │ │ │ │ (NextAuth)│ │ (Stripe) │ │ (Resend) │ │ Services │ │ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ │ DATA LAYER │ │ ┌────────────────────────────────────────────────────┐ │ │ │ Prisma ORM → MongoDB │ │ │ └────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘
## Directory Structure Explained
### `/app` - Next.js App Router
- **Purpose**: All routes and pages
- **Pattern**: File-system based routing
- **Key files**:
- `page.tsx` - Route page component
- `layout.tsx` - Shared layout wrapper
- `loading.tsx` - Loading UI
- `error.tsx` - Error boundary
### `/actions` - Server Actions
- **Purpose**: Server-side business logic
- **Pattern**: "use server" directive
- **Security**: Runs on server only, secure by default
### `/components` - React Components
- **Purpose**: Reusable UI components
- **Structure**:
- `/ui` - Base Shadcn components
- `/shared` - Shared app components
- Feature-specific components in feature directories
### `/db` - Database
- **Purpose**: Database client and utilities
- **Pattern**: Centralized Prisma instance
### `/services` - External Integrations
- **Purpose**: Third-party service wrappers
- **Examples**: Stripe, SendGrid, Analytics
### `/lib` - Utilities
- **Purpose**: Helper functions and utilities
- **Examples**: Validation, formatting, constants
### `/hooks` - React Hooks
- **Purpose**: Reusable React hooks
- **Pattern**: `use` prefix (e.g., `useUser`)
### `/types` - TypeScript Types
- **Purpose**: Shared type definitions
- **Pattern**: Interface and type declarations
### `/schemas` - Validation Schemas
- **Purpose**: Zod schemas for validation
- **Usage**: Forms, API inputs, database validation
## Data Flow Examples
### User Authentication Flow
User → Login Form → Server Action (auth) → NextAuth → Prisma → MongoDB → Session Created → Redirect to Dashboard
### Payment Flow
User → Pricing Page → Checkout → Stripe Checkout → Payment Success → Webhook → Update User Subscription → Database Updated → User Notified
### Content Creation Flow
User → Dashboard Form → Server Action → Validate Input → Prisma Create → MongoDB → Success Response → UI Updated → Confirmation
## Key Technologies Integration
### Authentication (NextAuth.js)
- **Config**: `/auth.config.ts` and `/auth.ts`
- **Providers**: Credentials, Google, GitHub
- **Session**: JWT-based
- **Database**: Prisma adapter for MongoDB
### Payments (Stripe)
- **Setup**: `/services/stripe.ts`
- **Webhooks**: `/app/api/webhooks/stripe/route.ts`
- **Events**: subscription.created, subscription.updated, payment.succeeded
### Database (MongoDB + Prisma)
- **Schema**: `/prisma/schema.prisma`
- **Client**: `/db/index.ts`
- **Migrations**: Prisma migrate
### Email (Resend/SendGrid)
- **Templates**: `/email-templates/`
- **Service**: `/services/email.ts`
- **Usage**: Transactional emails, newsletters
## Security Architecture
### Middleware Protection
```typescript
// /middleware.ts
export default auth((req) => {
// Auth checks
// Route protection
// Rate limiting
})
- JWT verification
- CSRF protection
- Rate limiting
- Input validation (Zod schemas)
- Secrets in
.env.local - Never commit
.envfiles - Use
.env.exampleas template
- Default to Server Components
- Use
'use client'only when needed:- Event handlers
- Browser APIs
- State management (useState, useEffect)
- Connection pooling (handled by Prisma)
- Indexes on frequently queried fields
- Select only needed fields
- Static pages where possible
- Dynamic routes with revalidation
- API routes with cache headers
GitHub → Vercel → Production
↓
Preview Deployments
↓
MongoDB Atlas
↓
External Services (Stripe, Resend)
- Stateless server actions
- JWT-based sessions (no session store)
- Database connection pooling
- MongoDB indexes for performance
- CDN for static assets
- Image optimization (Next.js Image)
- Console.error for development
- Production: Add Sentry or similar
- User events tracking
- Performance monitoring
- Business metrics
- Create feature directory in
/app - Add server actions in
/actions - Create database models if needed
- Add UI components
- Update navigation
- Add SDK to dependencies
- Create service wrapper in
/services - Add environment variables
- Initialize in appropriate location
- Document usage
- Create in
/app/api/[route]/route.ts - Implement HTTP methods
- Add authentication
- Handle errors
- Document in API docs
---
## 📄 File 3: `/docs/coding-patterns.md`
```markdown
# Coding Patterns & Best Practices
This document outlines the standard patterns used throughout SaaSPilot. Follow these patterns to maintain consistency and enable AI coding agents to understand and extend the codebase effectively.
## Table of Contents
1. [Server Actions](#server-actions)
2. [API Routes](#api-routes)
3. [Database Operations](#database-operations)
4. [Component Patterns](#component-patterns)
5. [Form Handling](#form-handling)
6. [Error Handling](#error-handling)
7. [Type Definitions](#type-definitions)
---
## Server Actions
### Basic Pattern
```typescript
'use server'
import { auth } from '@/auth'
import { db } from '@/db'
import { actionSchema } from '@/schemas/action-schema'
import { revalidatePath } from 'next/cache'
/**
* @ai-context Performs [specific action description]
* @ai-safe-to-modify Yes
* @returns Promise with success/error result
*/
export async function performAction(
formData: FormData
): Promise<{ success?: boolean; error?: string; data?: any }> {
// 1. Authenticate
const session = await auth()
if (!session?.user?.id) {
return { error: 'Unauthorized' }
}
// 2. Validate input
const validatedFields = actionSchema.safeParse({
field1: formData.get('field1'),
field2: formData.get('field2'),
})
if (!validatedFields.success) {
return { error: 'Invalid fields' }
}
const { field1, field2 } = validatedFields.data
try {
// 3. Perform database operation
const result = await db.model.create({
data: {
userId: session.user.id,
field1,
field2,
},
})
// 4. Revalidate if needed
revalidatePath('/dashboard')
// 5. Return success
return { success: true, data: result }
} catch (error) {
console.error('Action failed:', error)
return { error: 'Something went wrong' }
}
}
'use server'
import { z } from 'zod'
const inputSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
})
type ActionInput = z.infer<typeof inputSchema>
type ActionResult = { success?: boolean; error?: string; data?: any }
export async function typedAction(input: ActionInput): Promise<ActionResult> {
// Same pattern as above
}// /app/api/resource/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import { db } from '@/db'
/**
* @ai-context Fetches [resource description]
* @ai-auth-required Yes
*/
export async function GET(req: NextRequest) {
try {
// 1. Authenticate
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
// 2. Get query parameters
const searchParams = req.nextUrl.searchParams
const param = searchParams.get('param')
// 3. Fetch data
const data = await db.model.findMany({
where: { userId: session.user.id },
})
// 4. Return response
return NextResponse.json({ data })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}export async function POST(req: NextRequest) {
try {
// 1. Authenticate
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
// 2. Parse body
const body = await req.json()
// 3. Validate
const validated = schema.parse(body)
// 4. Process
const result = await db.model.create({
data: {
...validated,
userId: session.user.id,
},
})
// 5. Return
return NextResponse.json({ data: result }, { status: 201 })
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: 'Validation failed', details: error.errors },
{ status: 400 }
)
}
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}const newRecord = await db.model.create({
data: {
field1: value1,
field2: value2,
// Relations
user: {
connect: { id: userId }
}
},
// Include relations if needed
include: {
relatedModel: true
}
})// Find one
const record = await db.model.findUnique({
where: { id: recordId },
include: { relations: true }
})
// Find many with filtering
const records = await db.model.findMany({
where: {
userId,
status: 'active',
},
orderBy: { createdAt: 'desc' },
take: 10,
skip: 0,
})
// Find first
const first = await db.model.findFirst({
where: { email },
})const updated = await db.model.update({
where: { id: recordId },
data: {
field1: newValue,
updatedAt: new Date(),
},
})const deleted = await db.model.delete({
where: { id: recordId },
})const result = await db.$transaction(async (tx) => {
// Multiple operations
const user = await tx.user.update({ ... })
const log = await tx.auditLog.create({ ... })
return { user, log }
})// Default: Server Component (no 'use client')
import { auth } from '@/auth'
import { db } from '@/db'
/**
* @ai-context Displays [component purpose]
* @ai-type Server Component
*/
export default async function ComponentName() {
// Can directly fetch data
const session = await auth()
const data = await db.model.findMany()
return (
<div>
{/* JSX */}
</div>
)
}'use client'
import { useState, useEffect } from 'react'
interface Props {
initialData?: SomeType
}
/**
* @ai-context Interactive component for [purpose]
* @ai-type Client Component
* @ai-state-management useState, custom hooks
*/
export function ComponentName({ initialData }: Props) {
const [state, setState] = useState(initialData)
// Effects, handlers, etc.
return (
<div>
{/* Interactive JSX */}
</div>
)
}'use client'
import { useFormState, useFormStatus } from 'react-dom'
import { performAction } from '@/actions/action-name'
/**
* @ai-context Form for [purpose]
* @ai-action-binding performAction server action
*/
export function FormComponent() {
const [state, formAction] = useFormState(performAction, null)
return (
<form action={formAction}>
<input name="field1" required />
<input name="field2" required />
<SubmitButton />
{state?.error && <p className="text-red-500">{state.error}</p>}
</form>
)
}
function SubmitButton() {
const { pending } = useFormStatus()
return (
<button type="submit" disabled={pending}>
{pending ? 'Submitting...' : 'Submit'}
</button>
)
}'use client'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
const formSchema = z.object({
name: z.string().min(2, 'Name too short'),
email: z.string().email('Invalid email'),
})
type FormData = z.infer<typeof formSchema>
export function ZodForm() {
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
name: '',
email: '',
},
})
async function onSubmit(data: FormData) {
const result = await performAction(data)
if (result.error) {
// Handle error
}
}
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
<input {...form.register('name')} />
{form.formState.errors.name && (
<p>{form.formState.errors.name.message}</p>
)}
{/* More fields */}
</form>
)
}try {
const result = await riskyOperation()
return { success: true, data: result }
} catch (error) {
console.error('Operation failed:', error)
// Specific error types
if (error instanceof PrismaClientKnownRequestError) {
if (error.code === 'P2002') {
return { error: 'Record already exists' }
}
}
// Generic error
return { error: 'Something went wrong' }
}'use client'
import { useEffect } from 'react'
/**
* @ai-context Error boundary for [feature]
*/
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
console.error('Error:', error)
}, [error])
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={reset}>Try again</button>
</div>
)
}// Generated automatically from Prisma schema
import { User, Post, Subscription } from '@prisma/client'
// With relations
type UserWithProfile = User & {
profile: Profile | null
}// /types/index.ts
export interface ApiResponse<T> {
success: boolean
data?: T
error?: string
}
export type UserRole = 'user' | 'admin' | 'moderator'
export interface PaginatedResult<T> {
items: T[]
total: number
page: number
pageSize: number
}interface ComponentProps {
// Required
id: string
title: string
// Optional
subtitle?: string
className?: string
// Callbacks
onSubmit?: (data: FormData) => void
// Children
children?: React.ReactNode
}- Components:
PascalCase.tsx(e.g.,UserDashboard.tsx) - Utilities:
kebab-case.ts(e.g.,format-date.ts) - Actions:
kebab-case.ts(e.g.,create-user.ts) - Types:
PascalCase.tsorindex.ts(e.g.,User.ts)
- Constants:
UPPER_SNAKE_CASE(e.g.,MAX_FILE_SIZE) - Functions:
camelCase(e.g.,getUserById) - Components:
PascalCase(e.g.,UserProfile) - Boolean variables:
isX,hasX,shouldX(e.g.,isLoading)
- Models:
PascalCase(e.g.,User,BlogPost) - Fields:
camelCase(e.g.,createdAt,userId) - Enum values:
UPPER_SNAKE_CASEorcamelCase
/**
* Retrieves user data by ID
*
* @param userId - The unique user identifier
* @param includeProfile - Whether to include profile data
* @returns Promise resolving to user data or null
* @throws {PrismaClientKnownRequestError} If database query fails
*
* @ai-context Core user data retrieval function
* @ai-dependencies Prisma, Auth session
* @ai-modify-safe Yes - can extend with additional includes
*/
export async function getUserById(
userId: string,
includeProfile = false
): Promise<UserWithProfile | null> {
// Implementation
}// Calculate subscription end date based on plan duration
// Monthly plans: +30 days, Annual plans: +365 days
const endDate = plan === 'monthly'
? addDays(new Date(), 30)
: addYears(new Date(), 1)/**
* @ai-context This handles Stripe webhook events
* @ai-modify-careful This is security-sensitive code
* @ai-test-required Yes - changes should be thoroughly tested
* @ai-dependencies Stripe SDK, User model, Email service
*/
---
## 📄 File 4: `/docs/api-documentation.md`
```markdown
# API Documentation
## Overview
All API routes are located in `/app/api/` and follow RESTful conventions.
## Authentication
Most endpoints require authentication via NextAuth session.
```typescript
// Headers required
{
"Cookie": "next-auth.session-token=..."
}
- Development:
http://localhost:3000/api - Production:
https://your-domain.com/api
Get current user profile
Auth Required: Yes
Response:
{
"data": {
"id": "user_id",
"name": "John Doe",
"email": "john@example.com",
"image": "https://...",
"role": "user"
}
}Update user profile
Auth Required: Yes
Request Body:
{
"name": "John Doe",
"bio": "Developer"
}Response:
{
"success": true,
"data": { /* updated user */ }
}Get user's current subscription
Auth Required: Yes
Response:
{
"data": {
"id": "sub_id",
"status": "active",
"planId": "pro",
"currentPeriodEnd": "2024-12-31T00:00:00.000Z"
}
}Create Stripe checkout session
Auth Required: Yes
Request Body:
{
"priceId": "price_xxx",
"successUrl": "/dashboard",
"cancelUrl": "/pricing"
}Response:
{
"sessionId": "cs_xxx",
"url": "https://checkout.stripe.com/..."
}Handle Stripe webhook events
Auth Required: No (Stripe signature verification)
Events Handled:
checkout.session.completedcustomer.subscription.createdcustomer.subscription.updatedcustomer.subscription.deletedinvoice.payment_succeededinvoice.payment_failed
All errors follow this structure:
{
"error": "Error message",
"code": "ERROR_CODE",
"details": { /* optional */ }
}Status Codes:
200- Success201- Created400- Bad Request401- Unauthorized403- Forbidden404- Not Found500- Server Error
- Standard: 100 requests per 15 minutes per IP
- Authentication: 5 failed attempts per 15 minutes
- Webhooks: No limit (but signature verified)
Template for new API routes:
// /app/api/new-endpoint/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
export async function GET(req: NextRequest) {
const session = await auth()
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
// Implementation
return NextResponse.json({ data })
}Add documentation here after creating new endpoints.
---
## 📄 File 5: `/CLAUDE.md` (Root Level)
```markdown
# Building with Claude - Quick Start Guide
Welcome! This guide helps AI coding agents (Claude, Cursor, etc.) quickly understand and work with SaaSPilot.
## 🚀 Quick Setup
1. **Environment Setup**:
```bash
cp .env.example .env.local
# Fill in required variables
- Install Dependencies:
npm install- Database Setup:
npx prisma generate
npx prisma db push- Run Development Server:
npm run devVisit: http://localhost:3000
Before making changes, read these files IN ORDER:
/docs/ai-instructions.md- Core instructions and conventions/docs/architecture.md- System architecture overview/docs/coding-patterns.md- Standard code patterns/docs/api-documentation.md- API reference
# 1. Read the prompt template
# 2. Follow the pattern in /docs/coding-patterns.md
# 3. Create feature structure:
/app/feature-name/
├── page.tsx
├── components/
└── layout.tsx
/actions/feature-name/
└── action.tsSee: /prompts/add-new-feature.md
See: /prompts/create-api-endpoint.md
See: /prompts/modify-database-schema.md
See: /prompts/add-payment-plan.md
See: /prompts/customize-ui-component.md
✅ Comprehensive JSDoc comments on all major functions
✅ Consistent naming conventions throughout codebase
✅ Type-safe with TypeScript
✅ Clear folder structure with purpose-specific directories
✅ Modular architecture - easy to extend
✅ Detailed error handling patterns
✅ Ready-to-use examples in /examples directory
/app → Pages and routes (Next.js App Router)
/actions → Server actions (business logic)
/components → React components
/ui → Base components (Shadcn)
/shared → Shared app components
/db → Database client
/services → Third-party integrations
/lib → Utility functions
/hooks → React hooks
/types → TypeScript types
/schemas → Zod validation schemas
/prisma → Database schema
/docs → Documentation (AI instructions)
/prompts → Task templates for AI agents
/examples → Complete example projects
// Check if user is authenticated
import { auth } from '@/auth'
const session = await auth()
if (!session?.user) {
// Handle unauthorized
}// Always use Prisma
import { db } from '@/db'
const user = await db.user.findUnique({
where: { id: userId }
})'use server'
export async function myAction(formData: FormData) {
// 1. Auth check
// 2. Validation
// 3. Database operation
// 4. Return result
}// Use Shadcn/ui components
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
// Tailwind for styling
<div className="flex items-center gap-4">
<Button variant="default">Click me</Button>
</div>/auth.ts,/auth.config.ts- Authentication core/middleware.ts- Request middleware/prisma/schema.prisma- Database schema (requires migration)/app/api/webhooks/- Webhook handlers (security-sensitive)
# Type checking
npm run type-check
# Linting
npm run lint
# Build test
npm run buildnpm install package-name
# Update after adding packages
npx prisma generate # If DB-related- Check logs: Console in development
- Database: Use
npx prisma studioto view data - API testing: Use Thunder Client or Postman
- Type errors: Run
npm run type-check
- Check
/docsfor specific guidance - Look at
/examplesfor similar implementations - Review
/promptsfor task templates - Ask for clarification before making major changes
DO: ✅ Read relevant docs before coding ✅ Follow established patterns ✅ Add comments for complex logic ✅ Use TypeScript types ✅ Test changes locally ✅ Update documentation when adding features
DON'T:
❌ Modify core auth/security files without understanding
❌ Skip validation in server actions
❌ Ignore TypeScript errors
❌ Add dependencies without necessity
❌ Commit .env files
❌ Break existing patterns without reason
# Development
npm run dev # Start dev server
npm run build # Production build
npm run start # Start production server
# Database
npx prisma studio # Visual database browser
npx prisma generate # Regenerate Prisma client
npx prisma db push # Push schema changes
npx prisma migrate dev # Create migration
# Code Quality
npm run lint # Run ESLint
npm run type-check # TypeScript check- Documentation:
/docsdirectory - Examples:
/examplesdirectory - Templates:
/promptsdirectory - Architecture:
/docs/architecture.md - Patterns:
/docs/coding-patterns.md
Try this:
- Read
/docs/ai-instructions.md - Look at
/examplesfor reference - Choose a task from
/prompts - Follow the pattern
- Test your changes
Good luck coding! 🚀
---
## 📄 File 6: `/prompts/add-new-feature.md`
```markdown
# Prompt: Add New Feature
Use this template when asking AI to add a completely new feature to SaaSPilot.
## Template
I need to add a new feature to SaaSPilot: [FEATURE NAME]
Feature Description: [Describe what the feature does]
User Story: As a [user type], I want to [action] so that [benefit].
Requirements:
- [Requirement 1]
- [Requirement 2]
- [Requirement 3]
Database Changes Needed:
- New model(s): [Model names]
- Update existing model: [Which one]
- New fields: [List fields]
UI Components Needed:
- New page(s): [Page names and routes]
- New components: [Component names]
- Forms: [What forms]
- Dashboards/views: [What views]
API/Actions Needed:
- Server actions: [List actions]
- API routes: [List endpoints]
- External integrations: [Any third-party services]
Authentication:
- Public feature (no auth required)
- Requires authentication
- Requires specific role: [role name]
Before you start:
- Read /docs/ai-instructions.md
- Review /docs/coding-patterns.md
- Check /examples for similar features
- Follow the established patterns
Acceptance Criteria:
- Feature works as described
- Follows coding patterns
- Has proper error handling
- Is type-safe (TypeScript)
- Has appropriate authentication
- Database schema is updated
- UI is responsive and accessible
Please implement this feature step by step, explaining each part.
## Example Usage
I need to add a new feature to SaaSPilot: Task Management
Feature Description: Users can create, update, delete, and view their tasks. Tasks have titles, descriptions, due dates, and status (todo, in-progress, done).
User Story: As a logged-in user, I want to manage my tasks so that I can track my work.
Requirements:
- Create new tasks with title, description, due date
- View all my tasks in a list
- Update task status and details
- Delete tasks
- Filter tasks by status
Database Changes Needed:
- New model: Task
- id (string, primary key)
- title (string)
- description (string, optional)
- status (enum: TODO, IN_PROGRESS, DONE)
- dueDate (datetime, optional)
- userId (string, foreign key)
- createdAt (datetime)
- updatedAt (datetime)
UI Components Needed:
- New page: /dashboard/tasks
- Components:
- TaskList (displays all tasks)
- TaskItem (individual task card)
- TaskForm (create/edit form)
- TaskFilters (filter by status)
API/Actions Needed:
- Server actions:
- createTask
- updateTask
- deleteTask
- getTasks (with filters)
Authentication:
- Requires authentication
- Users can only see/manage their own tasks
Please implement this feature step by step, explaining each part.
# Prompt: Create API Endpoint
Use this template when you need to add a new API route.
## Template
I need to create a new API endpoint in SaaSPilot.
Endpoint Details:
- Path: /api/[path]
- Methods: [GET/POST/PUT/DELETE]
- Purpose: [What this endpoint does]
Authentication:
- Public endpoint
- Requires authentication
- Requires specific role: [role]
Request Format:
[For GET] Query Parameters:
- param1 (type): description
- param2 (type, optional): description
[For POST/PUT] Body (JSON):
{
"field1": "value",
"field2": 123
}Response Format:
Success (200/201):
{
"data": {
// response data
}
}Error (400/401/500):
{
"error": "Error message",
"code": "ERROR_CODE"
}Database Operations:
- Read from: [model name]
- Write to: [model name]
- Update: [model name]
- Delete from: [model name]
Validation Requirements:
- Field1: [validation rules]
- Field2: [validation rules]
Additional Notes: [Any special requirements, rate limiting, caching, etc.]
Before implementing:
- Check /docs/api-documentation.md for existing endpoints
- Follow pattern in /docs/coding-patterns.md (API Routes section)
- Use consistent error handling
Please create this endpoint following SaaSPilot patterns.
## Example Usage
I need to create a new API endpoint in SaaSPilot.
Endpoint Details:
- Path: /api/tasks
- Methods: GET, POST
- Purpose: Fetch user tasks and create new tasks
Authentication:
- Requires authentication
Request Format:
[GET] Query Parameters:
- status (string, optional): filter by status (todo/in-progress/done)
- limit (number, optional): max results (default 50)
[POST] Body (JSON):
{
"title": "Task title",
"description": "Task description",
"dueDate": "2024-12-31T00:00:00.000Z",
"status": "todo"
}Response Format:
Success GET (200):
{
"data": [
{
"id": "task_id",
"title": "Task 1",
"status": "todo",
"dueDate": "2024-12-31T00:00:00.000Z",
"createdAt": "2024-01-01T00:00:00.000Z"
}
],
"total": 10
}Success POST (201):
{
"data": {
"id": "task_id",
"title": "New Task",
"status": "todo"
}
}Database Operations:
- Read from: Task
- Write to: Task
Validation Requirements:
- title: required, min 1 char, max 200 chars
- description: optional, max 1000 chars
- status: required, enum (todo/in-progress/done)
- dueDate: optional, valid date in future
Please create this endpoint following SaaSPilot patterns.
# Prompt: Modify Database Schema
Use this template when you need to change the Prisma schema.
## Template
I need to modify the database schema in SaaSPilot.
Change Type:
- Add new model
- Add fields to existing model
- Modify existing fields
- Add relations
- Delete model/fields
- Add indexes
Model Name: [Model name]
Changes Needed:
[For new model]
model ModelName {
id String @id @default(cuid())
field1 String
field2 Int?
userId String
user User @relation(fields: [userId], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}[For adding fields] Add to existing [ModelName]:
- field1: Type (description)
- field2: Type (description)
[For modifications] Change:
- field1: from [current type] to [new type]
- Reason: [why this change]
Migration Strategy:
- Safe migration (no data loss)
- Requires data migration
- Default values needed
Impact Analysis: Affects:
- Existing data (how?)
- API endpoints (which ones?)
- UI components (which ones?)
- Server actions (which ones?)
Related Code Updates: After schema change, update:
- [File/component 1]
- [File/component 2]
- TypeScript types
- Validation schemas
Steps to Implement:
- Update /prisma/schema.prisma
- Run: npx prisma format
- Run: npx prisma generate
- Run: npx prisma db push (or migrate dev)
- Update affected code
- Test thoroughly
Please help me implement these database changes safely.
## Example Usage
I need to modify the database schema in SaaSPilot.
Change Type:
- Add new model
Model Name: Task
Changes Needed:
model Task {
id String @id @default(cuid())
title String
description String?
status TaskStatus @default(TODO)
dueDate DateTime?
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([userId])
@@index([status])
}
enum TaskStatus {
TODO
IN_PROGRESS
DONE
}Also need to add relation to User model:
model User {
// ... existing fields
tasks Task[]
}Migration Strategy:
- Safe migration (no data loss)
- New model, no existing data affected
Impact Analysis: Affects:
- Existing data: None (new model)
- API endpoints: Need to create new endpoints
- UI components: Need to create task management UI
- Server actions: Need to create task CRUD actions
Related Code Updates: After schema change, update:
- Create /actions/tasks/ directory with CRUD actions
- Create /app/dashboard/tasks/ page
- Create task-related components
- Add TaskStatus type to /types/index.ts
- Create validation schemas in /schemas/task-schema.ts
Steps to Implement:
- Update /prisma/schema.prisma
- Run: npx prisma format
- Run: npx prisma generate
- Run: npx prisma db push
- Create related files (actions, pages, components)
- Test task creation, reading, updating, deletion
Please help me implement these database changes safely.
# Troubleshooting Guide
Common issues and solutions when working with SaaSPilot.
## Database Issues
### Error: "Prisma Client is not generated"
```bash
# Solution: Generate Prisma client
npx prisma generate- Check DATABASE_URL in
.env.local - Verify MongoDB is running
- Check network/firewall settings
- Test connection:
npx prisma db pull
# Reset database (WARNING: deletes all data)
npx prisma migrate reset
# Or push schema without migration
npx prisma db push- Check NEXTAUTH_SECRET is set
- Verify NEXTAUTH_URL matches your domain
- Clear browser cookies
- Check middleware.ts configuration
- Verify OAuth credentials in
.env.local - Check redirect URLs in OAuth provider settings
- Google: http://localhost:3000/api/auth/callback/google
- GitHub: http://localhost:3000/api/auth/callback/github
- Check webhook secret (STRIPE_WEBHOOK_SECRET)
- Verify endpoint URL in Stripe dashboard
- Use Stripe CLI for local testing:
stripe listen --forward-to localhost:3000/api/webhooks/stripe- Check webhook is properly configured
- Verify handleStripeWebhook function
- Check Stripe dashboard for event history
- Look for errors in webhook logs
# Check for errors
npm run type-check
# Common fixes:
# 1. Regenerate Prisma types
npx prisma generate
# 2. Update dependencies
npm install
# 3. Clear Next.js cache
rm -rf .next# Clear cache and reinstall
rm -rf node_modules package-lock.json
npm install- Verify RESEND_API_KEY
- Check "from" email is verified domain
- Check email template path
- Review Resend dashboard for errors
- Verify SENDGRID_API_KEY
- Check sender email is verified
- Review SendGrid activity feed
- Check email content for spam triggers
# Kill process on port 3000
# Mac/Linux:
lsof -ti:3000 | xargs kill -9
# Windows:
netstat -ano | findstr :3000
taskkill /PID [PID] /F- Check file watcher limits (Linux)
- Restart dev server:
npm run dev - Clear
.nextfolder:rm -rf .next
- Restart dev server after changing
.env.local - Check variable names (no NEXT_PUBLIC_ for server-side)
- Verify
.env.localexists and not in .gitignore
- Check database query efficiency
- Add indexes to frequently queried fields
- Use
selectto limit returned fields - Implement pagination for large datasets
# Clear cache
rm -rf .next
# Check for large dependencies
npx bundle-analyzer- User session is null
- Add authentication check:
if (!session?.user) return
- Trying to create duplicate record
- Check for existing record first
- Handle P2002 Prisma error code
- Middleware configuration issue
- Check NEXTAUTH_URL setting
- Clear cookies and try again
- Too many requests to API
- Implement exponential backoff
- Check rate limit configuration
// In server actions
console.log('Debug:', { variable1, variable2 })
// In Prisma queries
prisma.$on('query', (e) => {
console.log('Query:', e.query)
console.log('Duration:', e.duration, 'ms')
})npx prisma studio
# Opens visual database browser at localhost:5555npm run build
# Look for errors and warnings- Network tab: Check API calls
- Console: Check for errors
- Application tab: Check cookies/local storage
- Check documentation in
/docs - Review examples in
/examples - Search GitHub issues
- Check Next.js documentation
- Check Prisma documentation
- Review Stripe/Resend documentation
When reporting issues, include:
- Error message (full stack trace)
- Steps to reproduce
- Expected vs actual behavior
- Environment (Node version, OS)
- Relevant code snippets
- Screenshots if applicable
---
## Implementation Priority
### Phase 1 (Start Here - Essential for AI Coding)
1. Create `/docs` directory
2. Add `ai-instructions.md`
3. Add `architecture.md`
4. Add `coding-patterns.md`
5. Create `/CLAUDE.md` at root
6. Add JSDoc comments to main files
### Phase 2 (High Value)
7. Create `/prompts` directory with templates
8. Add `api-documentation.md`
9. Create setup automation script
10. Add troubleshooting.md
### Phase 3 (Nice to Have)
11. Create `/examples` with sample projects
12. Add component relationship maps
13. Create dependency visualizations
14. Add more prompt templates
---
## Success Criteria
After implementation, an AI coding agent should be able to:
✅ Understand the codebase structure in < 5 minutes
✅ Add a new feature following established patterns
✅ Create API endpoints without breaking conventions
✅ Modify database schema safely
✅ Find relevant examples quickly
✅ Troubleshoot common issues independently
✅ Generate consistent, maintainable code
---
## Notes for Implementation
1. **Start with documentation** - This is the foundation
2. **Be consistent** - Follow the patterns you establish
3. **Add examples** - Real code examples are more valuable than descriptions
4. **Keep it updated** - Document as you add features
5. **Test with AI** - Actually use Claude/Cursor to verify the docs work
---
## Additional Recommendations
### For Video Series
- Add a `/examples` folder with 5-10 complete mini-SaaS projects
- Each example should be fully documented
- Include a README showing what was built and how long it took
### For Marketing
- Create a comparison document: "SaaSPilot vs Other Boilerplates"
- Highlight the AI-coding-ready aspect
- Show time-to-market metrics
### For Pro Version
- Keep advanced features (Admin Dashboard, Blog, Analytics) in Pro
- Offer discount codes to video viewers
- Create upgrade path documentation
---
## Questions for You
Before implementing, consider:
1. **Which framework version are you on?** (Next.js 14/15?)
2. **Do you have existing documentation** that should be preserved?
3. **Are there custom features** not in standard Next.js that need special docs?
4. **What's your MongoDB setup?** (Atlas, local, Docker?)
5. **Priority timeline?** (Which phases to implement first?)
---
## Implementation Checklist
Use this checklist to track progress:
### Documentation
- [ ] Create `/docs` directory
- [ ] Add `ai-instructions.md`
- [ ] Add `architecture.md`
- [ ] Add `coding-patterns.md`
- [ ] Add `api-documentation.md`
- [ ] Add `troubleshooting.md`
### Root Level Files
- [ ] Create `CLAUDE.md`
### Prompts Directory
- [ ] Create `/prompts` directory
- [ ] Add `add-new-feature.md`
- [ ] Add `create-api-endpoint.md`
- [ ] Add `modify-database-schema.md`
- [ ] Add `add-payment-plan.md`
- [ ] Add `customize-ui-component.md`
### Code Enhancements
- [ ] Add JSDoc comments to server actions
- [ ] Add JSDoc comments to API routes
- [ ] Add JSDoc comments to major components
- [ ] Add file headers with AI context
### Examples (Optional)
- [ ] Create `/examples` directory
- [ ] Add example project 1
- [ ] Add example project 2
- [ ] Add example project 3
### Scripts (Optional)
- [ ] Create `/scripts` directory
- [ ] Add `setup-ai-dev.sh`
- [ ] Add `generate-docs.js`
- [ ] Add `validate-structure.js`
---
**Ready to implement? Start with Phase 1 and work through the checklist systematically.**