CLAUDE.md TemplatesCLAUDE.md Template

CLAUDE.md Template: Next.js + TypeScript AI Search SaaS with Supabase, Clerk, Stripe

CLAUDE.md Template for building a complete AI Search Engine SaaS with Next.js, TS, Supabase, Clerk, Stripe, semantic indexing, filters, ranking, and analytics.

CLAUDE.md templateCLAUDE.md TemplateNext.jsTypeScriptSupabaseClerkStripesemantic indexingAI search SaaSvector searchanalytics

Target User

Developers building a production-grade AI Search SaaS with Next.js, Supabase, Clerk, Stripe

Use Cases

  • scaffold an AI search SaaS
  • define architecture and file structure
  • setup authentication and billing
  • enable semantic indexing and ranking
  • integrate analytics

Markdown Template

CLAUDE.md Template: Next.js + TypeScript AI Search SaaS with Supabase, Clerk, Stripe

# CLAUDE.md

Project role: You are Claude Code. Build a production‑ready AI Search Engine SaaS using Next.js (App Router), TypeScript, Supabase (Postgres with pgvector), Clerk for authentication, Stripe for billing, semantic indexing, filters, ranking, and analytics.

Architecture rules:
- Use Next.js App Router with TypeScript. Separate frontend, backend API routes, and server components.
- Supabase is the source of truth for data and embeddings; use pgvector for vector columns.
- Clerk handles authentication; enforce SSR-authenticated pages and protected API routes.
- Stripe handles billing; implement customer records, subscriptions, webhooks, and invoice events.
- Implement semantic indexing with vector search; store embeddings in a dedicated vectors column and index using Postgres GIN with pgvector.
- Build a dedicated search API that accepts query, optional filters, ranking parameters, and returns results ordered by relevance and recency.
- Maintain a clear separation of concerns: data access (db layer), business logic (service layer), API surface, and UI components.
- Use environment-based feature flags for production vs. development.

File structure rules:
- /src/app/                         # Next.js App Router
- /src/pages/                       # Optional if using App Router alongside /src/app
- /src/components/                  # UI components
- /src/lib/                         # utility and config (env, API clients)
- /src/db/                          # migrations, SQL, and schema definitions
- /src/services/                    # integration with Clerk, Stripe, embeddings, analytics
- /src/hooks/                       # React and server hooks
- /src/styles/                      # CSS/SCSS
- /public/                          # static assets
- /scripts/                         # migrations, seeding, deployment helpers
- /types/                           # TypeScript types and schemas

Authentication rules:
- ClerkProvider wraps the app; pages with useAuth or with SSR authentication for server components.
- All sensitive endpoints require authentication; refresh tokens validated on the server.
- Use role-based access for admin-like tasks (billing, data management).
- Do not expose user credentials or tokens to the client outside Clerk.

Database rules:
- Supabase with Row Level Security (RLS) enabled.
- Tables: users, docs, embeddings, analytics_events, subscriptions, customers, invoices.
- Policies:
  - PUBLIC: allow SELECT on non-sensitive data.
  - AUTHENTICATED: allow SELECT/INSERT/UPDATE on user-scoped data (docs, analytics).
- Provide sample policy SQL:
  -- Enable RLS and policies:
  ALTER TABLE users ENABLE ROW LEVEL SECURITY;
  CREATE POLICY "Users can view their own data" ON users FOR SELECT USING (auth.uid() = user_id);
- Use foreign keys and constraints for data integrity.

Validation rules:
- Use Zod for request validation in API routes: schemas for search, indexing, and analytics events.
- Validate input types and required fields; provide detailed error messages for invalid requests.

Security rules:
- Do not hardcode API keys; load from environment variables.
- Use CSRF protection on state-changing endpoints; set appropriate SameSite cookies.
- Sanitize user input; avoid dynamic SQL; use parameterized queries.
- Enforce least privilege for database roles in all deployments.

Testing rules:
- Unit tests for services and db helpers with Vitest.
- Integration tests for API routes using supertest or Playwright for end-to-end flows.
- Performance tests for indexing and search latency.
- Include tests for security controls (auth, CSRF, input validation).

Deployment rules:
- Deploy with Vercel or a similar platform; ensure environment variables are set (NEXT_PUBLIC_*, SUPABASE_URL, SUPABASE_ANON_KEY, CLERK_FRONTEND_API, STRIPE_SECRET, OPENAI_API_KEY).
- Run migrations on deployment; seed data as needed.
- Configure webhooks for Stripe in production.
- Set cache policies for search results and embeddings.

Things Claude must not do:
- Do not reveal secret API keys or credentials.
- Do not bypass authentication or authorization.
- Do not generate client-side code that exposes private tokens.
- Do not hardcode secrets in source files.
- Do not perform destructive actions without explicit confirmation in the template.

Overview

CLAUDE.md template for building a complete AI Search Engine SaaS using Next.js, TypeScript, Supabase, Clerk, Stripe, with semantic indexing, filters, ranking, and analytics. This template targets a production-grade stack and provides a ready-to-paste CLAUDE.md block that you can adapt for your product.

Direct answer: This CLAUDE.md template gives you a turnkey blueprint to implement a Next.js-based AI search SaaS with vector search (pgvector in Supabase), authenticated access via Clerk, flexible billing via Stripe, and robust analytics for search quality and usage.

When to Use This CLAUDE.md Template

  • You are building a production AI Search SaaS with a modern React/Next.js frontend and a Postgres-backed backend.
  • You need semantic indexing with vector search for document corpora and user queries.
  • You require user authentication and role-based access via Clerk.
  • You want subscription billing and customer management via Stripe.
  • You want clear boundaries for architecture, file structure, validation, security, and testing.
  • You need a ready-to-paste CLAUDE.md template to onboard your team quickly.

Copyable CLAUDE.md Template

# CLAUDE.md

Project role: You are Claude Code. Build a production‑ready AI Search Engine SaaS using Next.js (App Router), TypeScript, Supabase (Postgres with pgvector), Clerk for authentication, Stripe for billing, semantic indexing, filters, ranking, and analytics.

Architecture rules:
- Use Next.js App Router with TypeScript. Separate frontend, backend API routes, and server components.
- Supabase is the source of truth for data and embeddings; use pgvector for vector columns.
- Clerk handles authentication; enforce SSR-authenticated pages and protected API routes.
- Stripe handles billing; implement customer records, subscriptions, webhooks, and invoice events.
- Implement semantic indexing with vector search; store embeddings in a dedicated vectors column and index using Postgres GIN with pgvector.
- Build a dedicated search API that accepts query, optional filters, ranking parameters, and returns results ordered by relevance and recency.
- Maintain a clear separation of concerns: data access (db layer), business logic (service layer), API surface, and UI components.
- Use environment-based feature flags for production vs. development.

File structure rules:
- /src/app/                         # Next.js App Router
- /src/pages/                       # Optional if using App Router alongside /src/app
- /src/components/                  # UI components
- /src/lib/                         # utility and config (env, API clients)
- /src/db/                          # migrations, SQL, and schema definitions
- /src/services/                    # integration with Clerk, Stripe, embeddings, analytics
- /src/hooks/                       # React and server hooks
- /src/styles/                      # CSS/SCSS
- /public/                          # static assets
- /scripts/                         # migrations, seeding, deployment helpers
- /types/                           # TypeScript types and schemas

Authentication rules:
- ClerkProvider wraps the app; pages with useAuth or with SSR authentication for server components.
- All sensitive endpoints require authentication; refresh tokens validated on the server.
- Use role-based access for admin-like tasks (billing, data management).
- Do not expose user credentials or tokens to the client outside Clerk.

Database rules:
- Supabase with Row Level Security (RLS) enabled.
- Tables: users, docs, embeddings, analytics_events, subscriptions, customers, invoices.
- Policies:
  - PUBLIC: allow SELECT on non-sensitive data.
  - AUTHENTICATED: allow SELECT/INSERT/UPDATE on user-scoped data (docs, analytics).
- Provide sample policy SQL:
  -- Enable RLS and policies:
  ALTER TABLE users ENABLE ROW LEVEL SECURITY;
  CREATE POLICY "Users can view their own data" ON users FOR SELECT USING (auth.uid() = user_id);
- Use foreign keys and constraints for data integrity.

Validation rules:
- Use Zod for request validation in API routes: schemas for search, indexing, and analytics events.
- Validate input types and required fields; provide detailed error messages for invalid requests.

Security rules:
- Do not hardcode API keys; load from environment variables.
- Use CSRF protection on state-changing endpoints; set appropriate SameSite cookies.
- Sanitize user input; avoid dynamic SQL; use parameterized queries.
- Enforce least privilege for database roles in all deployments.

Testing rules:
- Unit tests for services and db helpers with Vitest.
- Integration tests for API routes using supertest or Playwright for end-to-end flows.
- Performance tests for indexing and search latency.
- Include tests for security controls (auth, CSRF, input validation).

Deployment rules:
- Deploy with Vercel or a similar platform; ensure environment variables are set (NEXT_PUBLIC_*, SUPABASE_URL, SUPABASE_ANON_KEY, CLERK_FRONTEND_API, STRIPE_SECRET, OPENAI_API_KEY).
- Run migrations on deployment; seed data as needed.
- Configure webhooks for Stripe in production.
- Set cache policies for search results and embeddings.

Things Claude must not do:
- Do not reveal secret API keys or credentials.
- Do not bypass authentication or authorization.
- Do not generate client-side code that exposes private tokens.
- Do not hardcode secrets in source files.
- Do not perform destructive actions without explicit confirmation in the template.

Recommended Project Structure

my-ai-search-saas/
├── src/
│   ├── app/                      # Next.js App Router
│   │   ├── layout.tsx
│   │   ├── page.tsx
│   │   └── [pipeline]/          # example dynamic routes
│   ├── components/
│   │   ├── SearchBar.tsx
│   │   └── ResultCard.tsx
│   ├── hooks/
│   │   └── useSearch.ts
│   ├── lib/
│   │   ├── apiClient.ts
│   │   └── clerkClient.ts
│   ├── services/
│   │   ├── embeddings.ts
│   │   ├── billing.ts
│   │   └── analytics.ts
│   ├── db/
│   │   ├── migrations/
│   │   └── sql/
│   └── types/
│       └── index.d.ts
├── public/
├── scripts/
├── tsconfig.json
├── package.json

Core Engineering Principles

  • Single source of truth: Postgres with pgvector as the canonical data store for docs and embeddings.
  • Security by default: RLS, least privilege roles, server-side auth checks, and signed cookies.
  • Strong typing: TypeScript across the stack; exhaustive API input validation with Zod.
  • Observability: structured logging, metrics, and analytics for search quality and usage.
  • Performance: optimized vector search, pagination, and caching for hot queries.
  • Maintainability: clear module boundaries and test coverage from day one.

Code Construction Rules

  • Use TypeScript for frontend and backend; share types where possible.
  • Next.js App Router preferred; keep API routes under /src/app/api.
  • Store embeddings in a dedicated vectors column; index with pgvector GIN index.
  • Authorizable endpoints: protect API routes with Clerk session validation on the server.
  • Validate all inputs with Zod schemas; return consistent error payloads.
  • Keep secrets in environment variables; do not commit keys.
  • Prefer server components for data fetching to reduce client bundle size.

Security and Production Rules

  • Enable Row Level Security (RLS) on all user data and ensure policies enforce user scope.
  • Use secure cookies, HTTPOnly, and SameSite strict for session management.
  • Validate and sanitize all inputs; avoid dynamic SQL; use parameterized queries.
  • Audit webhook handling (Stripe) with signature verification and replay protection.
  • Implement rate limiting on sensitive endpoints; monitor for anomalies.

Testing Checklist

  • Unit tests for services, db helpers, and utilities with Vitest.
  • API integration tests for search, indexing, and analytics endpoints.
  • End-to-end tests for signup, login, document indexing, and search flows with Playwright.
  • Security tests for auth, CSRF, and access control.
  • Deployment validation: migrations run, environment variables loaded, and webhooks configured.

Common Mistakes to Avoid

  • Hardcoding secrets or API keys in source files.
  • Missing RLS policies or breaking user data isolation.
  • Skipping input validation, leading to SQL injection or API misuse.
  • Neglecting webhook verification and replay protection.
  • Overloading client with embeddings; fetch on demand with caching.

Related implementation resources: AI Use Case for Policy Documents and Internal Question Answering.

FAQ

What is the CLAUDE.md Template used for?
It provides a complete blueprint to implement a production-grade AI Search SaaS using Next.js, TypeScript, Supabase, Clerk, Stripe, and semantic indexing.
Which stack is covered?
Next.js (App Router) + TypeScript + Supabase (Postgres with pgvector) + Clerk + Stripe, with semantic indexing, filters, and analytics.
How do I start indexing documents?
Indexing involves persisting docs in Supabase, generating embeddings via an embeddings service, and storing vectors for semantic search.
How is authentication secured?
Authentication is handled by Clerk; API routes validate sessions; server components fetch user data securely.
Where do I configure environment variables?
Environment variables are defined in deployment configs and never hardcoded in code.