Building Multi-Tenant Enterprise SaaS with Next.js, SurrealDB, Auth, RBAC, SSO, Billing, Admin Portal, and Audit Logs
Build a production-minded multi-tenant SaaS foundation in 60 minutes using Next.js App Router, SurrealDB as the complete backend, custom functions for business logic, and a deployable architecture for Vercel and Cloudflare.
Course Snapshot
- Duration: 60 minutes
- Level: Intermediate to Advanced
- Format: Fast-paced implementation walkthrough
- Primary stack: Next.js 14 App Router, React, TypeScript, SurrealDB, NextAuth/Auth.js, Stripe-style billing architecture, Vercel, Cloudflare
- Outcome: A working blueprint for a secure multi-tenant SaaS application with tenant isolation, authentication, authorization, billing hooks, admin surfaces, and audit logging.
Who This Is For
This course is for founders, product engineers, full-stack developers, and AI SaaS builders who want to move from a single-tenant prototype to an enterprise-ready SaaS architecture.
Prerequisites
- Basic TypeScript and React knowledge
- Familiarity with Next.js fundamentals
- Basic understanding of authentication and databases
- Node.js, npm, and Git installed locally
What You Will Build
A compact but production-oriented SaaS starter that includes:
- Tenant-aware workspace model
- User authentication and organization membership
- RBAC roles and permission checks
- SSO-ready identity architecture
- Billing subscription model and entitlement checks
- Admin portal structure
- Audit logs for sensitive actions
- SurrealDB schema, permissions, and custom functions
- Deployment strategy for Vercel and Cloudflare
60-Minute Agenda
0-5 min: Architecture Overview
- Map the SaaS control plane: users, tenants, memberships, roles, subscriptions, audit logs
- Decide what belongs in Next.js versus SurrealDB
- Understand request flow through App Router, middleware, server actions, and backend functions
5-12 min: Next.js App Router Foundation
- Create route groups for marketing, app, auth, and admin areas
- Use server components for secure data access
- Add server actions for tenant-scoped mutations
- Define environment variables for app URL, auth secret, SurrealDB endpoint, and billing provider
Suggested structure:
app/
(marketing)/
(auth)/login/
(app)/dashboard/
(admin)/admin/
api/auth/[...nextauth]/
lib/
auth/
db/
permissions/
billing/
audit/
12-22 min: SurrealDB as the Complete Backend
- Model tenants, users, memberships, roles, invoices, subscriptions, and audit events
- Use SurrealDB records and relations to represent organization membership
- Add database-level permissions for tenant isolation
- Use SurrealQL migrations for repeatable setup
Core records:
DEFINE TABLE tenant SCHEMAFULL;
DEFINE FIELD name ON tenant TYPE string;
DEFINE FIELD slug ON tenant TYPE string;
DEFINE FIELD created_at ON tenant TYPE datetime DEFAULT time::now();
DEFINE TABLE app_user SCHEMAFULL;
DEFINE FIELD email ON app_user TYPE string;
DEFINE FIELD name ON app_user TYPE option<string>;
DEFINE FIELD created_at ON app_user TYPE datetime DEFAULT time::now();
DEFINE TABLE membership SCHEMAFULL;
DEFINE FIELD user ON membership TYPE record<app_user>;
DEFINE FIELD tenant ON membership TYPE record<tenant>;
DEFINE FIELD role ON membership TYPE string;
DEFINE FIELD created_at ON membership TYPE datetime DEFAULT time::now();
DEFINE TABLE audit_log SCHEMAFULL;
DEFINE FIELD tenant ON audit_log TYPE record<tenant>;
DEFINE FIELD actor ON audit_log TYPE option<record<app_user>>;
DEFINE FIELD action ON audit_log TYPE string;
DEFINE FIELD target ON audit_log TYPE option<string>;
DEFINE FIELD metadata ON audit_log TYPE object;
DEFINE FIELD created_at ON audit_log TYPE datetime DEFAULT time::now();
22-32 min: Authentication and SSO-Ready Identity
- Add NextAuth/Auth.js with SurrealDB-backed user sessions
- Store user identity separately from tenant membership
- Support email/password, OAuth, and future SAML/OIDC SSO
- Add tenant selection after login
- Prepare domain-based SSO discovery, for example
acme.com -> tenant:acme
Implementation goals:
- Keep auth global
- Keep access tenant-scoped
- Never assume one user equals one tenant
- Make enterprise SSO an identity provider mapping, not a separate app
32-40 min: RBAC and Permission Checks
- Define roles: owner, admin, member, viewer, billing_admin
- Map roles to permissions such as
tenant:manage, member:invite, billing:manage, audit:read
- Add a
requirePermission() helper in server-side code
- Enforce tenant isolation in SurrealDB queries and server actions
Example permission helper:
export async function requirePermission({
userId,
tenantId,
permission,
}: {
userId: string;
tenantId: string;
permission: string;
}) {
const membership = await getMembership(userId, tenantId);
if (!membership) throw new Error("Tenant access denied");
const allowed = rolePermissions[membership.role]?.includes(permission);
if (!allowed) throw new Error("Permission denied");
return membership;
}
40-47 min: Extensions and Custom Functions for Business Logic
- Move critical rules close to the data layer
- Create SurrealDB custom functions for entitlement checks, audit writes, and tenant-safe mutations
- Use custom functions for reusable business logic such as
fn::can_manage_billing() or fn::write_audit_log()
Example custom function concept:
DEFINE FUNCTION fn::write_audit_log($tenant, $actor, $action, $target, $metadata) {
CREATE audit_log SET
tenant = $tenant,
actor = $actor,
action = $action,
target = $target,
metadata = $metadata,
created_at = time::now();
};
47-53 min: Billing, Entitlements, and Admin Portal
- Model subscription plans and tenant entitlements
- Add webhook route for billing events
- Update tenant subscription state from webhook payloads
- Gate premium features with entitlement checks
- Build admin routes for members, roles, billing, audit logs, and SSO settings
Admin portal sections:
- Overview
- Members and invitations
- Roles and permissions
- Billing and plan
- SSO configuration
- Audit logs
- Security settings
53-58 min: Audit Logs and Enterprise Controls
- Log authentication events, member changes, billing changes, role changes, and data exports
- Add filters by actor, action, date, and target
- Store immutable audit records
- Show audit history in the tenant admin portal
- Prepare export support for enterprise customers
Audit event examples:
member.invited
member.role_changed
billing.subscription_updated
sso.provider_connected
data.export_requested
admin.security_setting_changed
58-60 min: Deployment with Vercel and Cloudflare
- Deploy the Next.js app to Vercel
- Put Cloudflare in front for DNS, WAF, caching, and bot protection
- Use Cloudflare Workers when edge middleware or webhook normalization is needed
- Store secrets in Vercel project settings and Cloudflare environment bindings
- Configure preview deployments for every pull request
Recommended deployment split:
Cloudflare DNS/WAF/CDN -> Vercel Next.js App -> SurrealDB Cloud/Self-hosted
-> Billing Provider Webhooks
-> Identity Provider SSO
Hands-On Checkpoints
By the end of the session, learners should be able to:
- Explain the difference between authentication, authorization, tenancy, and entitlements
- Create a tenant-aware schema in SurrealDB
- Protect App Router pages and server actions with RBAC
- Add audit logs for sensitive actions
- Design SSO and billing integrations without hard-coding a single provider
- Deploy the system with Vercel and Cloudflare
Reference Implementation Tasks
- Bootstrap the Next.js App Router project.
- Add SurrealDB connection utilities.
- Create tenant, user, membership, subscription, and audit log tables.
- Add authentication and tenant selection.
- Implement RBAC helpers.
- Add SurrealDB custom functions for audit logging and entitlement checks.
- Create admin portal pages.
- Add billing webhook route and subscription state updates.
- Add audit log viewer.
- Deploy through Vercel with Cloudflare DNS and security controls.
Suggested Follow-Up Projects
- Add SAML SSO with tenant-specific identity provider settings
- Add SCIM provisioning for enterprise user lifecycle management
- Add usage-based billing with metered events
- Add row-level data export and audit archive retention
- Add SOC 2 readiness controls and admin evidence exports
Final Takeaway
A multi-tenant enterprise SaaS app is not just a login screen and a database. The durable foundation is tenant isolation, role-based authorization, SSO-ready identity, billing-aware entitlements, admin visibility, auditability, and a deployment model that can scale safely.