duhan
Blog

Avoiding Multiple Prisma Instances in NestJS

I accidentally ended up with multiple Prisma instances in my NestJS app.
Turns out, I was missing one important pattern Nest expects when using providers.

In my setup, I had a single prisma.service.ts file without a module declaration. Whenever I needed to query the database, I just imported PrismaService directly.
But Nest started throwing errors, because I hadn’t registered the service in any module’s providers.

Here’s the original file:

// prisma.service.ts (used everywhere directly, but without a module)
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 I went module by module, manually adding PrismaService to the providers array of each one. That looked like this:

// ❌ Wrong: adding PrismaService directly to each module
import { Module } from '@nestjs/common';
import { SomeController } from './some.controller';
import { SomeService } from './some.service';
import { PrismaService } from 'src/common/prisma.service';

@Module({
  controllers: [SomeController],
  providers: [SomeService, PrismaService],
})
export class SomeModule {}

But here’s the catch: every time you add a provider like that, Nest creates a new instance of it. So now I had 5–6 different Prisma clients, each unaware of the others.

The Fix

The fix was straightforward: wrap PrismaService in its own module and import that module wherever it’s needed.

// ✅ Correct: import PrismaModule once and share across modules
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaModule } from './prisma/prisma.module';

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

You just need to remove PrismaService from individual modules’ providers and add PrismaModule to their imports. That’s it.

Now the app works as expected, and I don’t get multiple database connections anymore.

🔗 Related posts