I’m working on a multi-tenant application using NestJS and Prisma. I want to dynamically set the databaseUrl based on the subdomain from my Next.js frontend. For example, if the subdomain is tenant1, I want to connect to tenant1_db, and if it’s tenant2, I want to connect to tenant2_db.
I’ve created a middleware to extract the subdomain from the request, but I’m not sure how to proceed with dynamically setting the databaseUrl in Prisma. Here’s my current middleware:
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class DynamicDbMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
const host = req.hostname;
const subdomain = host.split('.')[0]; // Extract the subdomain
req['subdomain'] = subdomain; // Attach the subdomain to the request object
next();
}
}