🦅 NestJS Advanced

What is NestJS's approach to multi-tenancy?

Answer

Multi-tenancy in NestJS can be implemented at different levels. Row-level (shared DB): include a tenantId in every database query. Use a REQUEST-scoped tenant service to extract the tenant from the request (JWT claim, subdomain, or header) and inject it into repositories. Schema-level (one DB, multiple schemas): TypeORM supports schema switching — a REQUEST-scoped data source factory creates a connection to the tenant's schema. Database-level (one DB per tenant): most isolated but complex — the tenant resolver dynamically selects the connection from a pool. For all approaches, use REQUEST-scoped providers to carry tenant context through the call stack. AsyncLocalStorage (ClsModule) is an alternative to REQUEST scope that avoids the performance penalty of scope bubbling for deeply nested providers.