Urvil Patel
urvil@portfolio:~$
0%
Urvil PatelUrvil Patel
•10 min read•Urvil Patel

Building a Production-Ready SaaS with Next.js

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:

  1. 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.
  2. 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.
  3. 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
User Request (Browser)
↓
Next.js App Router (Server Action or Route Handler)
↓
[Layer 1: Authentication] Validate Session Cookie & Tenant Context
↓
[Layer 2: Authorization] RBAC Permission Check (e.g. "team:invite_member")
↓
[Layer 3: Validation] Zod Schema Parsing & Type Coercion
↓
[Layer 4: Service Layer] Business Logic & Atomic Transactions
↓
[Layer 5: Data Access / Repository Layer] Drizzle ORM Queries
↓
PostgreSQL Database (Neon / PgBouncer Connection Pool)

Production SaaS Folder Structure

A production repository must maintain a predictable directory hierarchy where responsibilities are cleanly separated:

structure/project-layout.txt
TXT
src/
├── app/
│ ├── (auth)/ # Sign-in, sign-up, password reset
│ │ ├── sign-in/page.tsx
│ │ └── sign-up/page.tsx
│ ├── (dashboard)/[orgSlug]/ # Authenticated tenant-scoped workspace
│ │ ├── layout.tsx # Tenant validation & layout shell
│ │ ├── settings/page.tsx
│ │ └── billing/page.tsx
│ └── api/
│ ├── webhooks/stripe/ # Idempotent payment webhook route
│ └── auth/[...all]/ # Authentication endpoint handlers
├── components/
│ ├── ui/ # Reusable primitives (buttons, dialogs)
│ └── dashboard/ # Domain-specific UI widgets
├── actions/ # Next.js Server Actions (lightweight adapters)
├── lib/
│ ├── auth/ # Session and RBAC gatekeeper helpers
│ ├── stripe/ # Stripe SDK client & webhook helpers
│ └── env.ts # Validated runtime environment variables
├── db/
│ ├── schema/ # Modular Drizzle schemas
│ │ ├── organizations.ts
│ │ ├── users.ts
│ │ └── subscriptions.ts
│ └── index.ts # Pooled Drizzle client instance
├── services/ # Pure business logic and domain operations
├── repositories/ # Low-level database queries (Data Access Layer)
├── schemas/ # Shared Zod validation schemas
├── hooks/ # Client-side React hooks
└── types/ # Shared TypeScript domain contracts

Why Each Layer Exists:

  • 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.

Multi-Tenancy ModelOperational ComplexityCostTenant Isolation
Separate DB per TenantVery High (requires running 1000s of databases)HighAbsolute
Separate Schema per TenantModerate (migration scripts must run 1000x)ModerateHigh
Shared Schema with organization_idLow (standard migrations, instant provisioning)OptimalEnforced at Service Layer

1. Drizzle Schema Design

db/schema/organizations.ts
TS
import { pgTable, text, timestamp, uuid, index, pgEnum } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";
export const memberRoleEnum = pgEnum("member_role", ["owner", "admin", "member", "viewer"]);
export const subscriptionStatusEnum = pgEnum("subscription_status", [
"trialing",
"active",
"past_due",
"canceled",
]);
export const organizations = pgTable("organizations", {
id: uuid("id").defaultRandom().primaryKey(),
name: text("name").notNull(),
slug: text("slug").notNull().unique(),
stripeCustomerId: text("stripe_customer_id").unique(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
});
export const members = pgTable(
"members",
{
id: uuid("id").defaultRandom().primaryKey(),
organizationId: uuid("organization_id")
.references(() => organizations.id, { onDelete: "cascade" })
.notNull(),
userId: text("user_id").notNull(),
role: memberRoleEnum("role").default("member").notNull(),
joinedAt: timestamp("joined_at").defaultNow().notNull(),
},
(table) => [
index("org_members_idx").on(table.organizationId, table.userId),
]
);
export const membersRelations = relations(members, ({ one }) => ({
organization: one(organizations, {
fields: [members.organizationId],
references: [organizations.id],
}),
}));

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").

Role-Based Access Control (RBAC) Matrix

RoleRead DataCreate ResourcesManage Team / BillingDelete Organization
OwnerYesYesYesYes
AdminYesYesYesNo
MemberYesYesNoNo
ViewerYesNoNoNo

Type-Safe Permission Validator

lib/auth/rbac.ts
TS
export type Role = "owner" | "admin" | "member" | "viewer";
export type Permission =
| "org:delete"
| "org:update_settings"
| "members:invite"
| "members:remove"
| "billing:manage"
| "project:create";
const ROLE_PERMISSIONS: Record<Role, Permission[]> = {
owner: ["org:delete", "org:update_settings", "members:invite", "members:remove", "billing:manage", "project:create"],
admin: ["org:update_settings", "members:invite", "members:remove", "billing:manage", "project:create"],
member: ["project:create"],
viewer: [],
};
export function hasPermission(role: Role, requiredPermission: Permission): boolean {
return ROLE_PERMISSIONS[role].includes(requiredPermission);
}
export function assertPermission(role: Role, requiredPermission: Permission): void {
if (!hasPermission(role, requiredPermission)) {
throw new Error(`Unauthorized: Role '${role}' lacks permission '${requiredPermission}'`);
}
}

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
import { db } from "@/db";
import { organizations, members } from "@/db/schema/organizations";
import { eq, and } from "drizzle-orm";
import { assertPermission, Role } from "@/lib/auth/rbac";
export class OrganizationService {
/**
* Invites and assigns a new member inside an atomic transaction.
*/
static async addMemberToOrg(params: {
actorRole: Role;
organizationId: string;
targetUserId: string;
assignedRole: Role;
}) {
// 1. Authorization Gate
assertPermission(params.actorRole, "members:invite");
// 2. Business Rule: Only owners can promote someone to Admin
if (params.assignedRole === "admin" && params.actorRole !== "owner") {
throw new Error("Only organization owners can assign admin status.");
}
return await db.transaction(async (tx) => {
// Check existing membership to prevent duplicate entries
const existing = await tx
.select()
.from(members)
.where(
and(
eq(members.organizationId, params.organizationId),
eq(members.userId, params.targetUserId)
)
)
.limit(1);
if (existing.length > 0) {
throw new Error("User is already a member of this organization.");
}
const [newMember] = await tx
.insert(members)
.values({
organizationId: params.organizationId,
userId: params.targetUserId,
role: params.assignedRole,
})
.returning();
return newMember;
});
}
}

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.

app/api/webhooks/stripe/route.ts
TS
import { headers } from "next/headers";
import { stripe } from "@/lib/stripe";
import { db } from "@/db";
import { sql } from "drizzle-orm";
import type Stripe from "stripe";
export async function POST(req: Request) {
const body = await req.text();
const signature = (await headers()).get("stripe-signature");
if (!signature) {
return new Response("Missing stripe-signature header", { status: 400 });
}
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (err) {
return new Response(`Webhook Error: ${(err as Error).message}`, { status: 400 });
}
// Idempotency Gate: Track processed event IDs
const wasProcessed = await db.execute(sql`
INSERT INTO processed_events (event_id, event_type, created_at)
VALUES (${event.id}, ${event.type}, NOW())
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id;
`);
if (!wasProcessed.rows.length) {
return new Response(JSON.stringify({ received: true, duplicate: true }), { status: 200 });
}
switch (event.type) {
case "customer.subscription.updated":
case "customer.subscription.deleted": {
const subscription = event.data.object as Stripe.Subscription;
// Update organization subscription state deterministically
console.log(`Updated subscription ${subscription.id} to status ${subscription.status}`);
break;
}
}
return new Response(JSON.stringify({ received: true }), { status: 200 });
}

Server Actions: The Thin HTTP Adapter

Server Actions should remain lean adapters that validate inputs and delegate work to services:

actions/members.ts
TS
"use server";
import { z } from "zod";
import { OrganizationService } from "@/services/organization-service";
import { revalidatePath } from "next/cache";
const InviteMemberSchema = z.object({
organizationId: z.string().uuid(),
userId: z.string().min(1),
role: z.enum(["owner", "admin", "member", "viewer"]),
});
export async function inviteMemberAction(prevState: unknown, formData: FormData) {
const parsed = InviteMemberSchema.safeParse({
organizationId: formData.get("organizationId"),
userId: formData.get("userId"),
role: formData.get("role"),
});
if (!parsed.success) {
return { success: false, errors: parsed.error.flatten().fieldErrors };
}
try {
// Current authenticated session and role fetched from auth context
const currentActorRole = "admin"; // Mocked for demonstration
await OrganizationService.addMemberToOrg({
actorRole: currentActorRole,
organizationId: parsed.data.organizationId,
targetUserId: parsed.data.userId,
assignedRole: parsed.data.role,
});
revalidatePath(`/dashboard/settings/members`);
return { success: true };
} catch (error) {
return { success: false, message: (error as Error).message };
}
}

Production Security & Reliability Concerns

  1. Security Headers: Configure strict headers in next.config.ts (Strict-Transport-Security, X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin).
  2. Rate Limiting: Protect authentication and public API endpoints with a Sliding Window rate limiter using Upstash Redis.
  3. 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.
  4. 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:


Summary Architecture Checklist

  • Multi-tenancy uses row-level organization_id foreign keys with composite indexes.
  • Serverless connection pooler (Neon / PgBouncer) prevents database connection starvation.
  • Clear Layered Separation: Actions → RBAC Gate → Service Layer → Repository → Drizzle ORM.
  • Stripe webhooks use signature verification and an idempotent event registry.
  • Server Actions validate input using Zod schemas before touching domain services.
  • Zero-downtime expand-and-contract migrations ensure seamless deployments.
Topics:#Next.js#SaaS#PostgreSQL#Architecture#TypeScript#Drizzle ORM