Stop Wasting Weeks on SaaS Setup! Use This Fastify + tRPC Boilerplate
Stop Wasting Weeks on SaaS Setup! Use This Fastify + tRPC Boilerplate
What if I told you that the next 40 hours you were planning to spend configuring authentication, database schemas, and API routes could be reduced to 15 minutes? No, this isn't some no-code fantasy or a bloated framework that fights you at every turn. This is the raw, developer-first reality that thousands of engineers are quietly discovering.
Here's the painful truth most founders won't admit: building a SaaS from scratch in 2024 is a minefield of micro-decisions that drain your soul. Which ORM won't betray you six months in? How do you get type safety from database to UI without losing your mind? What auth solution actually works in production, not just in tutorials? And please, don't get me started on the AI integration rabbit hole—everyone wants GPT features, but nobody talks about the streaming, rate limiting, and error handling nightmares.
You've seen the abandoned side projects. The GitHub repos with three commits and a broken Docker↗ Bright Coding Blog setup. The "I'll finish it this weekend" promises that died in the trenches of npm install hell. What separates the shipped products from the graveyard of good intentions isn't talent—it's starting with a foundation that doesn't crumble when you add real users.
Enter the AI Fullstack SaaS Boilerplate by Alan Schneberger. This isn't another toy template. It's a battle-tested, production-grade monorepo that combines Fastify, tRPC, and React↗ Bright Coding Blog 19 into a cohesive architecture designed for speed, type safety, and AI-powered features. Already powering platforms like Nachonacho.com—the world's largest marketplace for Software & Services—this boilerplate is the secret weapon smart developers are using to ship faster and sleep better.
Ready to stop configuring and start coding? Let's tear this thing apart and see why it might just end your framework fatigue forever.
What is the AI Fullstack SaaS Boilerplate?
The AI Fullstack SaaS Boilerplate is an open-source, modern web application starter built by developer Alan Schneberger and available at github.com/alan345/AI-Fullstack-SaaS-Boilerplate. It represents a deliberate architectural choice: what if we took the best parts of the T3 stack but freed ourselves from Next.js↗ Bright Coding Blog?
This isn't a rejection of Next.js—it's a strategic divergence. By decoupling the frontend into static files, the boilerplate enables deployment to any cloud object storage (AWS S3, Cloudflare R2, Vercel, you name it) without server-side rendering complexity. The trade-off? This stack is optimized for web applications, not marketing websites. If SEO is your primary concern, look elsewhere. If shipping a dashboard, SaaS product, or AI tool is your goal, you've found your match.
The repository has been gaining serious traction in the developer community, with a star history that tells the story of organic growth by builders who've been burned by over-engineered alternatives. What makes it genuinely different is the obsessive focus on developer experience—every dependency was chosen not for hype, but for solving real problems at scale.
Fastify replaces Express for its superior performance and plugin architecture. tRPC eliminates the API contract guessing game with end-to-end TypeScript safety. Drizzle ORM brings type-safe SQL without the query builder bloat. Better Auth handles the authentication maze that used to consume entire weekends. And crucially, Server-Sent Events (SSE) power the AI chat features—no WebSocket server configuration required.
This is a stack built by someone who shipped, failed, refined, and shipped again. The kind of foundation you can bet your startup on.
Key Features That Separate It From the Pack
Let's dissect what makes this boilerplate irresistibly practical for modern SaaS development:
End-to-End Type Safety with tRPC
Forget API documentation that lies. Forget runtime errors from mismatched payloads. With tRPC, your frontend and backend share a single source of truth. Change a router input schema? TypeScript screams immediately. The video demonstration on trpc.io shows this in action—autocomplete for your API routes as natural as local function calls.
AI-Powered Chat with Server-Sent Events
The boilerplate doesn't just include OpenAI integration—it demonstrates production-ready streaming patterns. SSE was chosen deliberately over WebSockets: easier infrastructure, automatic reconnection, HTTP-compatible load balancing. Your AI features work behind standard corporate firewalls without begging IT for port exceptions.
Modern React Without the Baggage
React 19 with React Router v7 gives you client-side routing freedom without framework lock-in. Pair this with Tailwind CSS↗ Bright Coding Blog v4's utility-first approach, and you're styling at the speed of thought. No CSS-in-JS runtime overhead. No hydration mismatches. Just components that render where you put them.
Database-First Development with Drizzle
Drizzle ORM is the TypeScript-first query builder that feels like writing SQL—because you essentially are. Migrations, schema definitions, and query logic all carry full type inference. The pnpm run push command syncs your schema instantly during development.
Better Auth Integration
Authentication is where most boilerplates show their cracks. Better Auth provides a modern, framework-agnostic solution with support for multiple providers, session management, and the critical impersonation feature—essential for customer support scenarios where you need to debug user-specific issues.
pnpm Workspace Monorepo
Clean separation of client and server packages with shared types and utilities. Fast installs, strict dependency management, and disk space efficiency that matters when you're iterating rapidly.
Production Health Monitoring
Built-in health check endpoints at http://localhost:2022/health.trpc and http://localhost:2022 give your monitoring stack something concrete to verify. No more "is it up?" guesswork.
Real-World Use Cases Where This Shines
1. AI-Native SaaS Products
Building the next Jasper, Copy.ai, or internal AI tool? The SSE-based chat implementation gives you streaming LLM responses out of the box. The OpenAI integration pattern extends naturally to Anthropic, Cohere, or self-hosted models. Your users see words appear in real-time—the psychological difference between "loading..." and active generation is massive for retention.
2. Data-Intensive Dashboard Applications
The Zelda API integration example demonstrates external REST API consumption patterns that scale. Whether you're pulling from Stripe, Salesforce, or proprietary data sources, the tRPC router architecture keeps your data layer organized. The debounced search hook shows thoughtful UX patterns for large datasets.
3. Multi-Tenant B2B Platforms
With Better Auth's impersonation feature and Drizzle's relational capabilities, you can build true multi-tenant applications where customer support can diagnose issues in real-time. The static frontend deployment means each tenant's custom branding deploys independently without backend redeployment.
4. Rapid MVP Validation
Need to test a hypothesis by Friday? The seed data system, pre-configured auth flows, and deployment-ready build pipeline mean you're showing clickable prototypes while competitors are still choosing their stack. The Nachonacho.com team proved this works at scale.
Step-by-Step Installation & Setup Guide
Let's get you running in minutes, not hours. The boilerplate assumes you have Node.js 18+ and PostgreSQL↗ Bright Coding Blog installed.
Prerequisites
First, install pnpm globally if you haven't:
npm install -g pnpm
Ensure PostgreSQL is running and create the application database:
# Connect to PostgreSQL (replace 'user' with your actual postgres username)
psql -U user
# Create the database
CREATE DATABASE fsb;
\q
Repository Setup
Clone the repository and prepare your environment:
# Clone the boilerplate
git clone https://github.com/alan345/AI-Fullstack-SaaS-Boilerplate.git
cd AI-Fullstack-SaaS-Boilerplate
Environment Configuration
The boilerplate uses separate environment files for client and server. You'll need to rename the example files:
# Server environment (in root directory)
cp example.env .env
# Client environment
cd client
cp example.env .env
cd ..
Edit both .env files with your actual credentials—database connection strings, OpenAI API keys, auth secrets, and any external service configurations.
Install and Initialize
# Install all dependencies across the monorepo
pnpm install
# Push Drizzle schema to your database (creates tables)
pnpm run push
# Seed with initial data for development
pnpm run seed
Development Server
# This single command starts both client and server with hot reloading
pnpm run dev
Your application is now running. The server typically serves on port 2022, with the client development server proxying API requests appropriately.
Production Build
When you're ready to ship:
# Create optimized production builds
pnpm run build
# Start the production server
pnpm run start
The static frontend assets can be deployed to any CDN or object storage, while the Fastify server handles API requests independently.
REAL Code Examples from the Repository
Let's examine actual patterns from the boilerplate that demonstrate its architectural decisions.
Health Check Endpoint
The server includes a dead-simple health verification that your load balancer or monitoring can hit:
// Access at http://localhost:2022/health.trpc or http://localhost:2022
// This verifies both the HTTP server and tRPC router are responsive
While the exact implementation isn't shown in the README, the Fastify plugin architecture makes this trivial to extend. The key insight: health checks should validate your critical dependencies, not just return 200 OK. A proper production extension would verify database connectivity and external service reachability before declaring "healthy."
Database Seeding Pattern
The seed command (pnpm run seed) populates your development database with realistic data. Looking at the stack, this likely uses Drizzle's seed utilities:
// Typical pattern inferred from the Drizzle + PostgreSQL stack
import { db } from './db';
import { users, posts } from './schema';
async function seed() {
// Insert seed users with hashed passwords via Better Auth
const [adminUser] = await db.insert(users).values({
email: 'admin@example.com',
name: 'Admin User',
role: 'admin'
}).returning();
// Create related data demonstrating relational patterns
await db.insert(posts).values({
title: 'Welcome to FSB',
content: 'This is seed content for development',
authorId: adminUser.id
});
console.log('Database seeded successfully');
}
seed().catch(console.error);
This pattern is crucial for team onboarding—new developers have a populated, realistic database immediately, not empty tables and broken UI.
Client-Side Search with Debounce
The README highlights a custom debounce hook for search functionality. Here's how this typically implements in the React frontend:
// Custom hook for debounced search - prevents API spam on every keystroke
import { useState, useEffect } from 'react';
function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
// Set up the timeout to update debounced value after delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Cleanup: cancel timeout if value changes before delay completes
return () => {
clearTimeout(handler);
};
}, [value, delay]); // Re-run if value or delay changes
return debouncedValue;
}
// Usage in a search component with tRPC
function SearchComponent() {
const [searchTerm, setSearchTerm] = useState('');
const debouncedSearch = useDebounce(searchTerm, 300); // 300ms delay
// Only fetches when debouncedSearch changes (after user stops typing)
const { data: results } = api.search.query.useQuery(
{ term: debouncedSearch },
{ enabled: debouncedSearch.length > 2 } // Only search for 3+ characters
);
return (
<input
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search products..."
/>
);
}
The 300ms debounce is the sweet spot—responsive enough to feel instant, conservative enough to prevent unnecessary server load. Combined with tRPC's query caching, this pattern delivers snappy search without backend strain.
Server-Sent Events for AI Chat
This is where the boilerplate truly differentiates itself. SSE provides streaming AI responses without WebSocket complexity:
// Server-side: Fastify route handling SSE stream
import { FastifyReply } from 'fastify';
import OpenAI from 'openai';
async function chatStreamHandler(request, reply: FastifyReply) {
const { message } = request.body;
// Set SSE headers for streaming response
reply.raw.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
});
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// Create streaming completion
const stream = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: message }],
stream: true, // Enable streaming response
});
// Stream chunks to client as they arrive
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
// SSE format: data: {json}\n\n
reply.raw.write(`data: ${JSON.stringify({ content })}\n\n`);
}
// Signal stream completion
reply.raw.write('data: [DONE]\n\n');
reply.raw.end();
}
The client consumes this with the EventSource API or a tRPC subscription wrapper. No WebSocket server to configure. No connection management. No proxy headaches. Just HTTP doing what HTTP does well, with automatic reconnection handled by the browser.
Advanced Usage & Best Practices
Monorepo Boundary Discipline
Resist the temptation to import server-only code into client packages. The pnpm workspace structure enforces this at the package level—maintain strict separation between client/, server/, and shared packages/ for types and utilities.
Database Migration Strategy
While pnpm run push works for rapid development, production demands proper migrations. Generate migration files with Drizzle Kit before deploying:
pnpm drizzle-kit generate:pg
pnpm drizzle-kit migrate
Testing in CI/CD
The Playwright E2E tests require a running application. Structure your GitHub Actions to build first, start the server in background, then execute:
pnpm run build
pnpm run start &
sleep 5 # Wait for server ready
pnpm run test
Environment-Specific Configuration
The static frontend means environment variables are baked at build time. Use Vite's import.meta.env pattern with .env.production for deployment-specific values, or implement a lightweight runtime config endpoint for truly dynamic settings.
Scaling the SSE Architecture
For high-traffic AI features, consider Redis-backed SSE broadcasting. A single Fastify instance handles thousands of concurrent streams, but horizontal scaling requires shared state for multi-server deployments.
Comparison with Alternatives
| Feature | AI Fullstack SaaS Boilerplate | T3 Stack (Next.js) | RedwoodJS | Supabase Starter |
|---|---|---|---|---|
| Frontend Deployment | Any static hosting (S3, R2, etc.) | Vercel-optimized | Netlify/Vercel | Supabase Hosting |
| Framework Lock-in | Minimal (Fastify + React) | Next.js ecosystem | Redwood opinions | Supabase ecosystem |
| Type Safety | tRPC end-to-end | tRPC end-to-end | GraphQL + codegen | Partial (DB types) |
| AI Streaming | SSE built-in | Requires custom setup | Custom implementation | Edge functions |
| Auth Solution | Better Auth | NextAuth / Clerk | Built-in | Supabase Auth |
| Database ORM | Drizzle | Prisma | Prisma | Direct PostgreSQL |
| Performance | Fastify (2x Express) | Next.js server overhead | Redwood overhead | Edge-optimized |
| SEO Capability | Not designed for | Excellent | Good | Good |
| Learning Curve | Moderate | Moderate-High | High | Low |
Choose this boilerplate when: You need a decoupled architecture, plan to deploy frontend and backend independently, prioritize AI feature integration, or want maximum hosting flexibility.
Choose T3/Next.js when: SEO is critical, you want file-based routing, or Vercel's ecosystem benefits outweigh flexibility needs.
FAQ
Is this boilerplate suitable for beginners?
If you're comfortable with TypeScript and have built at least one full-stack app, you'll thrive. Complete beginners might find the monorepo structure and tRPC concepts challenging initially, but the documentation and working examples accelerate learning significantly.
Can I deploy the frontend and backend separately?
Absolutely—that's the architectural superpower here. The static React build deploys to any CDN (Cloudflare, AWS S3 + CloudFront, Vercel for SPA hosting), while Fastify runs on any Node.js-capable host (Render, Railway, Fly.io, AWS EC2/Fargate).
How does authentication work with the decoupled frontend?
Better Auth handles session management via HTTP-only cookies or token-based flows. The client package includes the necessary fetch interceptors to include credentials with API requests to your Fastify server.
Can I swap OpenAI for other LLM providers?
The SSE streaming pattern is provider-agnostic. Replace the OpenAI SDK initialization with Anthropic's @anthropic-ai/sdk, Cohere, or a local Ollama instance. The response streaming logic remains identical.
Is there Docker support for local development?
While not explicitly shown in the README, the PostgreSQL dependency and Node.js runtime make Docker Compose trivial to add. Many community forks likely include this—check the issues and discussions.
How production-ready is this really?
Nachonacho.com—a production marketplace with real revenue—runs on this stack. The health checks, build pipeline, and testing setup demonstrate production consciousness.
What's the migration path from this boilerplate?
Because dependencies are standard (not framework-wrapped), you can extract and evolve pieces independently. Your Drizzle schema migrates to any Node.js project. Your React components work in any React host. No vendor lock-in traps.
Conclusion: Your SaaS Foundation Starts Here
After dissecting the AI Fullstack SaaS Boilerplate, one thing is unmistakably clear: this isn't a toy for tutorial followers. It's a deliberate, opinionated, and proven architecture for developers who value shipping over configuring.
The decision to escape Next.js's gravitational pull isn't rebellion—it's strategic liberation. Static frontends on global CDNs. API servers scaling independently. AI features streaming through simple HTTP. Every choice reduces operational complexity while maintaining developer ergonomics.
What Alan Schneberger has built reflects hard-won lessons from production systems. The tRPC integration eliminates an entire category of bugs. Drizzle ORM brings SQL power without query builder bloat. Better Auth solves authentication without framework lock-in. And the SSE-based AI chat? That's the feature your competitors are still architecting meetings about.
The SaaS graveyard is full of perfect architectures that never shipped. This boilerplate is for builders who'd rather deploy on Tuesday and iterate on Wednesday than debate patterns in Discord for six months.
Your move. Star the repository, clone it, run pnpm install, and feel that rare sensation of a development environment that just works. The demo at fsb-client.onrender.com proves what's possible. Your version—customized, extended, launched—is waiting.
👉 Get the AI Fullstack SaaS Boilerplate on GitHub
Give it a star ⭐ if it saves you a week of setup. Consider sponsoring 💖 if it saves you a month. The best time to stop reinventing the wheel was last year. The second best time is right now.
Found this breakdown valuable? Share it with the developer who's been "starting their SaaS next week" for three months. They'll thank you later.
Outils recommandés
Explore on the BrightCoding network
Hand-picked resources from our other sites.
ObservedObserver/async-code: Parallel Claude Code Agents Explained
ObservedObserver/async-code is a self-hosted platform for running multiple Claude Code agents in parallel through a Codex-style web UI. Built with Next.js, Pyth...
Anthropic's Secret Weapon: Claude Agent SDK Demos Exposed
Discover Anthropic's official Claude Agent SDK demos—8 production-ready patterns for building AI agents including multi-agent research, streaming chat, and visu...
the0: Why Top Quants Are Ditching Proprietary Engines
Discover the0, the open-source algorithmic trading engine supporting 7 languages with production-grade microservices architecture. Deploy trading bots via Docke...
Continuez votre lecture
Why Alexandrie is the Ultimate Markdown Note-Taking App
Why CrossPaste is the Ultimate Game Changer for Clipboard Management
Why Chandra is the Ultimate OCR Tool for Handwriting and Tables
Stop Coding Alone: OPC-Skills Gives Your AI Agent Superpowers
Commentaires 0
Aucun commentaire pour l'instant. Soyez le premier à réagir !