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.
Previous
How do you implement health checks in NestJS?
Next
What is the cls-hooked/nestjs-cls module and when should you use it?
More NestJS Questions
View all →- Advanced What is the CQRS pattern and how does NestJS support it?
- Advanced How do you implement gRPC in NestJS?
- Advanced What is the NestJS Interceptor execution order and how do multiple interceptors interact?
- Advanced How does NestJS handle graceful shutdown?
- Advanced What is custom provider syntax in NestJS (useClass, useValue, useFactory)?