duhan
Blog

NestJS: Multiple Prisma Instance Problem

While working on a side project, I ran into a situation where the Prisma instance was created more than once.

The main reason for this was that I had a single file called prisma.service.ts without module declaration, so that when I wanted to make a database call, I would import this service into the file. However, NestJS was giving an error because I had not included prisma.service.ts in the providers of the corresponding module. So I added PrismaService to my modules one by one.

This is how NestJS works, if you want to use any injectable class in a different module, you need to provide the class to the module.

Broken Code

// solo prisma.service.ts file
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit() {
    await this.$connect();

    console.log('connected to db...');
  }
}

So, whenever I want to use prisma, I add PrismaService to corresponding module:

import { Module } from '@nestjs/common';
import { LinksController } from './links.controller';
import { LinksService } from './links.service';
import { PrismaService } from 'src/common/prisma.service';

@Module({
  controllers: [LinksController],
  // here
  providers: [LinksService, PrismaService],
})
export class LinksModule {}

What this means to NestJS is that “create a brand new PrismaService instance because it is provided in providers”. I had around 5-6 module like above.

Fix

Fix was quite easy. I added a separate Prisma module and import this into imports array of corresponding module file. Then, remove PrismaService from each module’s providers array.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaModule } from './prisma/prisma.module';

@Module({
  // here
  imports: [PrismaModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Now, Prisma is no longer creating more than one instance.