Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 42 ยท Data and Persistence

Connecting to a Database

Learn how to connect NestJS to a database: TypeORM, Prisma and MikroORM compared, module setup, async connection config, the repository seam and health checks.

Almost every real API stores data. Nest itself does not include a database layer: it is deliberately neutral, and it gives you the tools (modules, providers, configuration) to plug in whichever data library you prefer. That freedom raises the first design question of this chapter: which library, and how do you wire it in so that the rest of your code does not depend too tightly on the choice?

This lesson compares the three most common options, shows how each is registered as a module, and focuses on one idea that matters more than the library: put the database behind a repository, a small provider that your services call. You will use modules, custom providers and configuration from the earlier lessons. The framework and ORM code below is read-only, because it needs Node, npm and a database server. The runnable parts are honest stand-ins: a repository class backed by memory and then by node:sqlite, the SQLite module built into Node 24, with the same interface so you can see the swap.

Three common choices

Pick a data library

TypeORM Decorated entity classes. Has an official Nest module.
Prisma Schema file and a generated, typed client.
MikroORM Unit of work and identity map. Official Nest module.

Raw drivers and query builders such as Knex also work.

1 / 2

Each has trade-offs, and none is "the Nest way":

  • TypeORM maps TypeScript classes decorated with @Entity() to tables. It follows the classic ActiveRecord/Data Mapper style, and @nestjs/typeorm provides TypeOrmModule. It has been used with Nest for years, so many tutorials and examples use it.
  • Prisma starts from a schema.prisma file and generates a client with types for every model and query. You do not write entity classes; the generated client is the data layer. There is no official Nest module, but the recommended pattern is a small service that extends the generated client.
  • MikroORM uses entities too, but with an explicit unit of work and an identity map, so changes are tracked and flushed together. It has a @mikro-orm/nestjs package.

The examples in this chapter mostly use TypeORM-style code because the repository pattern is easiest to show with it, but every idea transfers. Version details change between major releases of these libraries, so treat the code as the shape of the solution and check the current guide of your library before copying.

Registering TypeORM

Install @nestjs/typeorm, typeorm and a driver for your database (for PostgreSQL, pg). Then register the connection once in the root module:

TypeScript
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      url: process.env.DATABASE_URL,
      autoLoadEntities: true,
      synchronize: false,
    }),
    UsersModule,
  ],
})
export class AppModule {}

autoLoadEntities: true collects the entities that feature modules register with forFeature(), so you do not list every entity in one central array. And synchronize must be false in production: with true, TypeORM changes the schema to match your classes on every start, and a renamed property can drop a column with its data. Schema changes belong in migrations, covered in Transactions and Migrations.

A hard-coded process.env read in a module decorator runs when the file is loaded, which can be before your configuration files are read. Use the async form from the dynamic modules lesson so values come from ConfigService:

TypeScript
TypeOrmModule.forRootAsync({
  inject: [ConfigService],
  useFactory: (config: ConfigService) => ({
    type: 'postgres',
    url: config.getOrThrow<string>('DATABASE_URL'),
    autoLoadEntities: true,
    synchronize: false,
  }),
})

A feature module then declares which entities it uses and injects a repository:

TypeScript
@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User) private readonly users: Repository<User>,
  ) {}

  findByEmail(email: string) {
    return this.users.findOneBy({ email });
  }
}

@InjectRepository(User) is just @Inject() with a token that forFeature() registered, the custom-provider mechanism at work.

Prisma and MikroORM in outline

Prisma needs one provider that owns the client's connection lifecycle. Nest calls onModuleInit when the module starts and onModuleDestroy (with shutdown hooks enabled) when the app stops:

TypeScript
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

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

  async onModuleDestroy() {
    await this.$disconnect();
  }
}

You then list PrismaService in a module's providers and exports, and services call this.prisma.user.findMany(). The generated client and its configuration (including how it connects) have changed in recent major versions, so follow the current Prisma guide for the generator and driver settings.

MikroORM registers with MikroOrmModule.forRoot({ ... }) and exposes an EntityManager and per-entity repositories through forFeature(). Because of its unit of work, you change loaded entities and call em.flush() to persist, which also makes it a natural fit for transactions.

The repository seam

Whichever library you pick, avoid scattering ORM calls through controllers. A repository is a provider with a handful of domain-shaped methods (findByEmail, add, listRecent). Services depend on it, and only the repository knows about SQL or the ORM. Benefits: services are easy to test with a fake repository, queries live in one place, and changing storage touches one class.

In Nest you can express the contract as an abstract class (it exists at runtime, so it works as a token without @Inject()) and bind it with a custom provider:

TypeScript
export abstract class UsersRepository {
  abstract findByEmail(email: string): Promise<User | null>;
  abstract add(user: NewUser): Promise<User>;
}

@Module({
  providers: [
    UsersService,
    { provide: UsersRepository, useClass: TypeOrmUsersRepository },
  ],
})
export class UsersModule {}

Don't overdo it. A thin repository around every table adds noise if it only forwards calls to the ORM's own repository. It pays off when it hides real query logic or when you want to swap implementations in tests.

Connection health and pooling

Database drivers keep a pool of connections and reuse them. Set the pool size to what the database can handle across all app instances (ten pods with a pool of 20 means 200 connections). A health endpoint tells the platform whether the app can reach its database. The @nestjs/terminus package provides indicators for this, for example TypeOrmHealthIndicator.pingCheck('database'), and Deployment and Performance wires it up properly.

Stand-in: a repository backed by memory

The first stand-in is plain JavaScript, not Nest. A service depends on a repository contract, and the first implementation keeps rows in an array. It follows the repository idea above, with constructor injection written by hand.

Node.js A service and an in-memory repository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The business rule (normalize the email) lives in the service; storage lives in the repository. Because UsersService only calls add and findByEmail, we can give it a different repository.

Stand-in: the same service on SQLite

Now the same UsersService runs on a real database engine, node:sqlite, which ships with Node 24 (it may print an experimental warning). The SQLite repository implements the same three methods, so the service is untouched. This is the swap that a custom provider ({ provide: UsersRepository, useClass: ... }) performs in Nest. Nest itself is not involved here.

Node.js Swap in a SQLite repository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output matches the in-memory version, with one difference that matters: the duplicate is now rejected by the database's UNIQUE constraint, so it stays correct even if two app instances race. The repository translates the driver's error into the domain error the service expects. Keep database constraints as the final safety net, and use application checks for friendly messages.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Does NestJS include its own database layer?

    Nest is data-layer neutral. It provides modules, providers and configuration, and you choose the library.
  2. 2. Why should synchronize be false for a TypeORM connection in production?

    With synchronize on, the schema is changed automatically to match your classes, which can drop columns. Migrations are reviewed, versioned and reversible.
  3. 3. What does @InjectRepository(User) do?

    It is @Inject() with a token derived from the entity. forFeature() registers the matching provider in the module.
  4. 4. What is the main benefit of putting storage behind a repository class?

    A repository isolates the data library, making services easier to test and storage easier to change. It does not by itself change performance.

Summary

  • Nest has no data layer of its own; common choices are TypeORM, Prisma and MikroORM, each registered through a module or provider.
  • Register the connection once (forRoot), preferably with forRootAsync and ConfigService, and let feature modules declare their entities with forFeature.
  • Never run synchronize: true in production; use migrations.
  • Keep ORM details inside repositories and let services depend on a contract, which makes tests and storage swaps simple.
  • Size the connection pool for all instances together, and expose a health check.
  • Database constraints (UNIQUE, foreign keys) are the last line of defense that application code cannot replace.

Next, model related data with entities, relations and pagination in Repositories, Entities and Relations.