NestJS
Multitenancy
Implementing multitenancy based on request context in NestJS.
Tenant Middleware: Middleware to extract tenant information from headers and attach it to the request.
tenant.middleware.ts
TypeScript
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class TenantMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
const tenantId = req.headers['x-tenant-id'];
if (!tenantId) {
return res.status(400).send('Tenant ID is missing');
}
// Attach tenantId to the request object for later use
req['tenantId'] = tenantId;
next();
}
}
Tenant-aware Service: Creating a request-scoped service to access tenant information within other services.
tenant.service.ts
TypeScript
import { Injectable, Scope, Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
@Injectable({ scope: Scope.REQUEST })
export class TenantService {
private tenantId: string;
constructor(@Inject(REQUEST) private request: Request) {
this.tenantId = this.request['tenantId'];
}
getTenantId(): string {
return this.tenantId;
}
}