The $10M AI SaaS Playbook

0) Project framing (paste first)

You are my senior full-stack engineer. We are building a production-ready web app: an AI research + writing assistant for students/researchers. Core user flow:

  1. user signs up

  2. creates a “Project”

  3. uploads/pastes sources (PDF/text/URLs later)

  4. writes in a rich editor

  5. uses AI tools: outline, rewrite, autocomplete, citations helper, summarize sources

  6. exports to DOCX/PDF

  7. subscriptions + usage limits

Constraints:

  • Use Next.js App Router + TypeScript

  • Postgres + Prisma

  • Auth (Clerk or NextAuth) — choose one and implement cleanly

  • Payments (Stripe) with monthly plan + free tier limits

  • AI: OpenAI-compatible SDK (use env vars, server-only)

  • Clean UI with Tailwind + shadcn/ui

  • Add analytics events (PostHog or simple DB events)

  • Security: rate limit AI endpoints, validate inputs (zod), avoid leaking secrets
    Generate code incrementally, with file paths and exact edits.

Before coding, propose architecture + folder structure + data model.

1) Repo + stack bootstrap

Create a new Next.js app-router TypeScript project with Tailwind, shadcn/ui, eslint, prettier. Add Prisma + Postgres. Provide commands + initial file tree. Implement a basic landing page, auth pages, and an authenticated dashboard route group.

2) Data model (Prisma)

Design Prisma schema for:

  • User (linked to auth provider id)

  • Project

  • Document (belongs to Project)

  • Source (belongs to Project; stores type: text/pdf/url later; store extractedText)

  • AIUsage (tracks tokens/credits per user per day/month)

  • Subscription (stripeCustomerId, status, plan, currentPeriodEnd)

  • Event (analytics: userId, name, properties JSON, createdAt)

Include indexes you’d actually want. Add migration + seed script.

3) Auth integration

Implement auth end-to-end (choose Clerk OR NextAuth and stick to it).
Requirements:

  • Signed-out users: can view landing page, pricing, login/signup

  • Signed-in users: dashboard, projects, editor

  • Middleware/route protection for /app/*

  • User provisioning: on first login, create User row in DB
    Show me exact files to create/edit.

4) Dashboard: Projects CRUD

Build the /app/dashboard page:

  • List projects

  • Create project modal

  • Rename + delete project

  • Each project card links to /app/projects/[projectId]
    Use server actions (or route handlers) + optimistic UI.
    Add toasts and loading states.

Also track events: ProjectCreated, ProjectDeleted.

5) Project page: Documents + Sources

On /app/projects/[projectId]:
Left column:

  • Documents list + “New document”

  • Sources list + “Add source (paste text)” for now

Main area:

  • if doc selected: open editor

  • else: empty state

Data requirements:

  • Each project can have many documents

  • Each document has content (store as JSON for editor) + title

  • Each source has name + rawText + extractedText (same for now)

Implement CRUD for docs and sources.

6) Rich editor (TipTap) with autosave

Integrate TipTap (or another solid rich-text editor) in the document view.
Requirements:

  • Autosave to DB (debounced) with “Saving…” indicator

  • Slash menu with a few blocks (heading, bullet list, quote)

  • Word count

  • Export-ready structure (don’t overcomplicate)

Store editor content as JSON in Document.contentJson.
Add “Export DOCX” later; just stub a button now.

7) AI service layer (server-only) + rate limiting

Create an AI module:

  • /lib/ai/client.ts (OpenAI-compatible client)

  • /lib/ai/prompts.ts (prompt templates)

  • /lib/ai/usage.ts (track & enforce limits)

  • /app/api/ai/* route handlers

Add rate limiting per user (e.g. Upstash or a simple in-memory/dev + DB-backed in prod).
Enforce free-tier daily limit (e.g. 30 requests/day) and paid tier higher.
Return friendly errors and show them in UI.

8) AI feature: “Outline from prompt”

Add a panel button: “Generate outline”.
UI:

  • Modal with a prompt field + optional style dropdown (Academic / Blog / Notes)

  • On submit: call /api/ai/outline with current doc title + prompt + (optional) sources context

  • Insert outline into editor at cursor (as headings + bullets)

Backend:

  • Gather up to 3 sources’ extractedText (truncate safely)

  • Build system+user prompt

  • Return structured markdown or JSON blocks

  • Convert response to TipTap nodes

Track events: OutlineGenerated.

9) AI feature: “Rewrite selection”

In editor toolbar:

  • Rewrite button opens menu: Shorter / Clearer / More formal / More persuasive

  • When user highlights text, send selection + mode to /api/ai/rewrite

  • Replace selection with rewritten text (preserve basic formatting if possible)

Include safety:

  • Max selection length

  • Show diff preview optional (simple)
    Track events: RewriteUsed.

10) AI feature: Autocomplete “Next sentence”

Implement a lightweight autocomplete:

  • User hits TAB at end of paragraph → fetch suggestion from /api/ai/continue

  • Show ghost text (gray) that user can accept (TAB) or dismiss (ESC)

  • Keep it fast: smaller model, short context window

Track events: AutocompleteAccepted, AutocompleteShown.

11) “Sources” grounding + citations (MVP)

Implement a citations helper MVP:

  • User clicks “Cite sources” → backend returns 3–5 bullet citations (title + quote snippet + “(Source: X)”)

  • Insert at cursor as a “References” section

  • For now, treat pasted text sources as “Source 1/2/3” with user-editable names

  • Add a “Find supporting quote” feature: given a claim, search extractedText via simple substring/TF-IDF (local) before calling AI

Track events: CitationsInserted.

12) Search within sources (local)

Implement a local search box on sources panel:

  • queries over extractedText

  • highlight matches

  • clicking a result opens a side drawer with snippet + copy button

No AI needed here.

13) Pricing + Stripe subscriptions

Implement Stripe:

  • Plans: Free, Pro

  • Free: daily AI request limit + max Projects (e.g. 3)

  • Pro: higher limits + unlimited projects
    Build:

  • /pricing page

  • Checkout session creation

  • Billing portal

  • Webhooks: subscription created/updated/canceled
    DB sync to Subscription table
    Gate features based on Subscription status.

14) Usage + limits UI

Add a usage widget in dashboard:

  • “AI requests used today: X / limit”

  • “Projects used: Y / limit”
    Show upgrade CTA when near limit.

15) Export DOCX/PDF (basic)

Add export:

  • Convert TipTap JSON → HTML

  • DOCX export using a library (or generate HTML doc)

  • PDF export via server-side render or browser print stylesheet
    Add an “Export” dropdown on editor.

16) Quality & security hardening

Add:

  • Zod validation for every API route

  • Server-side auth checks for every mutation

  • CSP headers

  • File upload stub (future) with safe MIME checks

  • Logging with request ids

  • Error boundary pages

17) Deploy checklist

Create:

  • env var checklist

  • database migration steps

  • Stripe webhook setup steps

  • cron (optional) for usage resets

  • basic monitoring notes

18) Final polish

Implement:

  • keyboard shortcuts cheat sheet

  • onboarding checklist on first project

  • empty states and skeleton loaders

  • dark mode toggle

Deliver a concise “What’s implemented” README section + how to run locally.

IMPORTANT OUTPUT FORMAT FOR EACH STEP

For every step you implement:

  1. brief plan

  2. exact file changes with paths

  3. code snippets

  4. commands to run

  5. what to click/test manually