js

Build Multi-Tenant SaaS with NestJS, Prisma, and PostgreSQL Row-Level Security Tutorial

Learn to build secure multi-tenant SaaS apps with NestJS, Prisma, and PostgreSQL RLS. Master tenant isolation, JWT auth, and scalable architecture patterns.

Build Multi-Tenant SaaS with NestJS, Prisma, and PostgreSQL Row-Level Security Tutorial

I’ve been thinking a lot about multi-tenant architectures lately. Why? Because in my own SaaS projects, I kept hitting walls when scaling beyond early adopters. The moment you need to securely separate customer data while maintaining performance, traditional approaches start crumbling. That’s when I turned to PostgreSQL’s Row-Level Security combined with NestJS and Prisma - a stack that transformed how I build scalable applications.

Multi-tenancy means one application serves many customers with isolated data. There are different approaches: separate databases per tenant (secure but costly), separate schemas (moderate isolation), or shared tables with RLS (efficient and scalable). I chose RLS because it balances security with operational simplicity. How does it actually work? Let me show you.

First, our Prisma schema defines tenant-aware models. Notice the tenantId field on every tenant-specific entity:

model User {
  id        String   @id @default(cuid())
  email     String   
  tenantId  String
  tenant    Tenant   @relation(fields: [tenantId], references: [id])
}

The magic happens in PostgreSQL with RLS policies. We create rules that automatically filter data based on tenant context:

CREATE POLICY tenant_users_policy ON users
  FOR ALL
  USING (tenant_id = current_setting('app.current_tenant_id'));

This policy ensures users only see data where tenant_id matches their session’s tenant ID. But how do we set that context securely? Through a PostgreSQL function:

CREATE FUNCTION set_tenant_id(tenant_id text) RETURNS void AS $$
BEGIN
  PERFORM set_config('app.current_tenant_id', tenant_id, true);
END;
$$ LANGUAGE plpgsql;

In our NestJS application, we create a Prisma service that executes this function before each tenant-specific operation:

@Injectable()
export class PrismaService extends PrismaClient {
  async setTenantContext(tenantId: string) {
    await this.$executeRaw`SELECT set_tenant_id(${tenantId})`;
  }
}

Now comes the crucial part: resolving tenants from incoming requests. We use middleware to identify tenants based on subdomains:

@Injectable()
export class TenantResolutionMiddleware implements NestMiddleware {
  constructor(private tenantService: TenantService) {}
  
  async use(req: Request, res: Response, next: NextFunction) {
    const subdomain = req.subdomains[0];
    const tenant = await this.tenantService.findBySubdomain(subdomain);
    if (!tenant) throw new NotFoundException('Tenant not found');
    
    req.tenant = tenant;
    req.tenantId = tenant.id;
    next();
  }
}

We then create guards to ensure tenant context exists before accessing protected routes:

@Injectable()
export class TenantGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    if (!request.tenantId) throw new ForbiddenException('Tenant required');
    return true;
  }
}

What about authentication? We embed the tenant ID in JWTs during login:

async login(user: User) {
  const payload = { 
    sub: user.id, 
    tenantId: user.tenantId 
  };
  return {
    access_token: this.jwtService.sign(payload),
  };
}

For tenant-aware services, we use a transaction wrapper that sets the context:

@Injectable()
export class UserService {
  constructor(private prisma: PrismaService) {}
  
  async getUsers(tenantId: string) {
    return this.prisma.withTenant(tenantId, () => {
      return this.prisma.user.findMany();
    });
  }
}

Handling custom domains? We store verified domains in our Tenant model and resolve them similarly to subdomains. But remember: always validate domain ownership before enabling!

When testing, we use Jest to simulate multi-tenant environments. Each test case creates a tenant context before operations:

test('users only see own data', async () => {
  await prisma.setTenantContext(tenantA.id);
  const users = await userService.findAll();
  expect(users).toHaveLength(3); // Only tenantA's users
});

Performance considerations? Monitor query execution times and connection pooling. I recommend PgBouncer for connection management and setting proper indexes on tenant_id columns. Watch out for N+1 queries - Prisma’s relation loading needs careful tuning.

Common pitfalls include forgetting to enable RLS on new tables (always check ALTER TABLE ... ENABLE ROW LEVEL SECURITY) and leaking tenant context between requests. Always reset tenant ID after each operation!

The beauty of this approach? We maintain a single database instance while guaranteeing data isolation. Security lives at the database level, not just application code. Have you considered how this might simplify your compliance requirements?

This architecture has served me well in production environments handling thousands of tenants. The initial setup requires careful planning, but the long-term maintenance benefits are substantial. What challenges have you faced with multi-tenancy?

If you found this useful, please share it with your network. I’d love to hear your experiences in the comments below - let’s keep the conversation going!

Keywords: multi-tenant SaaS NestJS, Prisma multi-tenancy tutorial, PostgreSQL row-level security RLS, NestJS tenant architecture, SaaS application development guide, multi-tenant database design, Prisma ORM multi-tenancy, NestJS authentication JWT tenant, subdomain routing multi-tenant, scalable SaaS backend development



Similar Posts
Blog Image
Build a Distributed Task Queue System with BullMQ Redis and TypeScript Complete Guide

Learn to build scalable task queues with BullMQ, Redis & TypeScript. Master job processing, error handling, monitoring & deployment. Complete tutorial with Express.js integration.

Blog Image
Build Multi-Tenant SaaS Applications with NestJS, Prisma, and PostgreSQL Row-Level Security

Learn to build scalable multi-tenant SaaS apps with NestJS, Prisma, and PostgreSQL RLS. Complete guide with secure tenant isolation and database-level security. Start building today!

Blog Image
Build a Distributed Task Queue System with BullMQ, Redis, and TypeScript: Complete Professional Guide

Learn to build a distributed task queue system with BullMQ, Redis & TypeScript. Complete guide with worker processes, monitoring, scaling & deployment strategies.

Blog Image
Complete Guide to Building Multi-Tenant SaaS Applications with NestJS, Prisma and PostgreSQL RLS Security

Learn to build secure multi-tenant SaaS apps with NestJS, Prisma & PostgreSQL RLS. Complete guide with authentication, tenant isolation & performance tips.

Blog Image
Build High-Performance Rate Limiting Middleware with Redis and Node.js: Complete Tutorial

Learn to build scalable rate limiting middleware with Redis & Node.js. Master token bucket, sliding window algorithms for high-performance API protection.

Blog Image
Node.js Event-Driven Microservices: Complete RabbitMQ MongoDB Architecture Tutorial 2024

Learn to build scalable event-driven microservices with Node.js, RabbitMQ & MongoDB. Master message queues, Saga patterns, error handling & deployment strategies.