Skip to main content

MULTI-TENANT

multi-tenant.ts

Workspace scoping, tenant isolation, role-based access.

Stark avatarStark

WHAT THIS PATTERN TEACHES

How to scope all data access to the current workspace and enforce tenant boundaries.

WHEN TO USE THIS

Any SaaS application with workspaces, teams, or organizations.

AT A GLANCE

export function scopedQuery<T>(workspace: string) {
  return db.query<T>()
    .where('workspace_id', workspace)
    // tenant isolation enforced
}

FRAMEWORK IMPLEMENTATIONS

TypeScript
import { db } from "@/lib/db";
import { ApiError } from "@/lib/errors";

type Role = "owner" | "admin" | "member" | "viewer";

interface TenantContext {
  workspaceId: string;
  userId: string;
  role: Role;
}

export async function getTenantContext(
  workspaceId: string,
  userId: string
): Promise<TenantContext> {
  const membership = await db.workspaceMember.findFirst({
    where: { workspaceId, userId },
  });
  if (!membership) {
    throw new ApiError("NOT_FOUND", "Workspace not found", 404);
← All Patterns