A battle-tested architectural blueprint for engineering scalable, multi-tenant B2B SaaS applications using Next.js App Router, Drizzle ORM, PostgreSQL, Better Auth, and Stripe.
Most Next.js tutorials demonstrate toy applications: single-file routes where React Server Components query the database directly with raw SQL or an ORM. While this is great for rapid prototyping, shipping an enterprise-grade multi-tenant B2B SaaS requires strict software engineering discipline.
In a real SaaS environment, you must guarantee strict tenant data isolation, enforce fine-grained Role-Based Access Control (RBAC), execute atomic multi-step database transactions, process idempotent payment webhooks, and maintain defense-in-depth security.
In this architectural guide, we dissect how to build a scalable, maintainable, production-ready SaaS on the Next.js App Router.
What Problem Are We Solving?
The primary failure mode of scaling Next.js applications is architectural coupling. When database access, authorization logic, and business validation are scattered directly across React components and Server Actions:
Security Vulnerabilities & Data Leaks: A developer forgets to include where(eq(posts.organizationId, currentOrgId)) in a component query, leaking one customer's private data to another.
Untestable Business Logic: Business rules (e.g., subscription seat caps, invitation expirations) cannot be unit-tested without mocking the entire Next.js HTTP execution context.
Database Connection Exhaustion: Serverless lambdas spin up hundreds of un-pooled connections directly to PostgreSQL, triggering database connection limits during traffic spikes.
To solve this, we implement a Layered Architecture with strict boundaries between the HTTP/Presentation layer, Domain Service layer, and Data Access layer.
The SaaS Request Lifecycle & Architecture
Every mutating request follows a unidirectional, defense-in-depth pipeline:
architecture/saas-pipeline.txt
TXT
1User Request (Browser)
2 ↓
3Next.js App Router (Server Action or Route Handler)
actions/: Acts purely as an HTTP controller adapter. It unpacks form data, checks session credentials, passes arguments to the service layer, and triggers revalidatePath().
services/: Contains zero React or Next.js code. Pure TypeScript business logic that can be tested with standard unit test runners (vitest / bun test).
repositories/: Isolates all SQL/Drizzle queries. If you change a table column name, you update one repository method rather than hunting through 50 components.
Database Architecture: PostgreSQL & Drizzle ORM
Multi-Tenancy Strategy: Row-Level Isolation
For B2B SaaS serving thousands of organizations, Row-Level Tenancy with an organization_id foreign key on every tenant-scoped table is the gold standard.
37exportconstmembersRelations=relations(members, ({ one }) => ({
38organization: one(organizations, {
39fields: [members.organizationId],
40references: [organizations.id],
41 }),
42}));
Connection Pooling with Serverless PostgreSQL
In serverless runtimes like Vercel or AWS Lambda, incoming traffic bursts can instantiate hundreds of concurrent containers. Connecting directly to standard PostgreSQL port 5432 will trigger FATAL: remaining connection slots are reserved for non-replication superuser connections.
Solution: Use a connection pooler like PgBouncer or Neon Serverless Pooling (-pooler connection string) configured with transaction-mode pooling.
Authentication & Authorization (RBAC)
Authentication verifies identity ("You are Alice"); Authorization verifies permissions ("Alice has permission to delete the project in Org Acme").
24thrownewError(`Unauthorized: Role '${role}' lacks permission '${requiredPermission}'`);
25 }
26}
Transactional Service Layer
The service layer contains pure business logic. Crucially, multi-table operations must execute inside a database transaction to guarantee ACID consistency:
services/organization-service.ts
TS
1import { db } from"@/db";
2import { organizations, members } from"@/db/schema/organizations";
3import { eq, and } from"drizzle-orm";
4import { assertPermission, Role } from"@/lib/auth/rbac";
5
6exportclassOrganizationService {
7/**
8 * Invites and assigns a new member inside an atomic transaction.
38thrownewError("User is already a member of this organization.");
39 }
40
41const [newMember] =awaittx
42 .insert(members)
43 .values({
44organizationId: params.organizationId,
45userId: params.targetUserId,
46role: params.assignedRole,
47 })
48 .returning();
49
50returnnewMember;
51 });
52 }
53}
Payments & Subscription Lifecycle with Stripe
A production subscription workflow must never rely on the browser client redirect to grant access. Users can close the tab or lose internet connectivity immediately after swiping their credit card.
All state transitions must be verified asynchronously via Stripe Webhooks.
Idempotent Webhook Handler
Because Stripe guarantees at-least-once delivery, webhooks can be retried multiple times for the same transaction. Without idempotency checks, you might dispatch duplicate emails, provision multiple subscriptions, or miscalculate billing limits.
Rate Limiting: Protect authentication and public API endpoints with a Sliding Window rate limiter using Upstash Redis.
Database Migrations (Expand and Contract): Never execute destructive migrations (DROP COLUMN) directly.
Phase 1 (Expand): Add new column, write to both old and new.
Phase 2 (Migrate): Backfill historical records.
Phase 3 (Contract): Remove legacy column after all application instances run the new code.
Audit Logs: Maintain an append-only audit_logs table recording actor_id, action, resource_id, and ip_address for SOC2 compliance.
Connecting AI to SaaS
Modern B2B applications frequently incorporate AI capabilities (e.g. document summarization, semantic search, generative assistants). When embedding AI into multi-tenant software:
Always enforce tenant-scoped vector filtering to prevent cross-customer data exposure.
Enforce strict token usage quotas per billing tier.
For an end-to-end breakdown of building AI pipelines and conversational agents, explore our deep-dive guides: