1

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();
  }
}

1 Answer 1

0

At a high level, you need to create a dynamic DB instance based on each request.

Request provider is what you are looking for

https://docs.nestjs.com/fundamentals/injection-scopes#request-provider

then you could create a database service. Something like this

@Injectable({ scope: Scope.REQUEST })
export class DatabaseProvider {
  private dbClient;

  constructor(
    @Inject(REQUEST) private readonly request: Request,
  ) {}

  getDbClient() {
    if (!this.dbClient) {
      const dbUrl = this.request.user?.dbUrl // get your subdomain or subdomain url here;
      this.dbClient = createClient(dbUrl);
    }

    return this.dbClient;
  }
}

then for any service or repository you will have to inject the DatabaseProvider and call getDbClient. With this singleton pattern each request should only create one DB client instance. Of course, your system creates new DB instance for each request which is a trade off unless you have pre-defined domains list and store their associated DB clients somewhere.

Happy coding.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you but my tenants are not that big i will manually store their dburls so i can stop creating new prisma clients what is the best way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.