TypeORM Integration

The @nestjs/typeorm package connects Nest to SQL databases using the TypeORM library.

SyntaxTypeOrmModule.forRoot(options)

Nest integrates with TypeORM, a popular Object-Relational Mapper, through the @nestjs/typeorm package. It lets you work with database tables as TypeScript classes.

Setup

Import TypeOrmModule.forRoot() in your root module with your connection settings. This is a dynamic module - you configure it once and TypeORM connects at startup.

Prisma is a popular alternative ORM; the next lesson touches on it. Either way, the Nest pattern of injecting a data layer into services stays the same.

Example

Example Β· typescript
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: 'postgres',
      database: 'app',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true, // dev only
    }),
  ],
})
export class AppModule {}

When to use it

  • A developer connects a NestJS API to a PostgreSQL database using TypeOrmModule.forRoot() so the app manages the connection pool automatically.
  • A team uses synchronize:true in development so TypeORM keeps the database schema in sync with entity changes without manual migrations.
  • An engineer uses TypeOrmModule.forRootAsync() to load database credentials from ConfigService rather than hard-coding them in the module.

More examples

Install TypeORM packages

Installs the three packages needed: the Nest TypeORM adapter, TypeORM itself, and the database driver.

Example Β· bash
npm install @nestjs/typeorm typeorm pg
# pg = PostgreSQL driver; use mysql2 for MySQL

Synchronous TypeORM setup

Configures TypeORM with PostgreSQL using forRoot, enabling autoLoadEntities so registered entity classes are picked up automatically.

Example Β· ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: 'secret',
      database: 'mydb',
      autoLoadEntities: true,
      synchronize: true,   // dev only
    }),
  ],
})
export class AppModule {}

Async setup via ConfigService

Loads database configuration asynchronously from ConfigService, keeping credentials out of source code.

Example Β· ts
TypeOrmModule.forRootAsync({
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: (cfg: ConfigService) => ({
    type: 'postgres',
    url: cfg.get('DATABASE_URL'),
    autoLoadEntities: true,
    synchronize: cfg.get('NODE_ENV') !== 'production',
  }),
})

Discussion

  • Be the first to comment on this lesson.