How to Connect PostgreSQL to NestJS with TypeORM

By Abdelilah Ommane · Backend Developer

Short answer

Install @nestjs/typeorm and pg, register TypeOrmModule.forRoot() with your Postgres connection in AppModule, define an @Entity() class, then inject a repository with @InjectRepository(Entity) to read and write data.

1. Install dependencies

npm i @nestjs/typeorm typeorm pg

2. Configure the connection

// app.module.ts
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: process.env.DB_HOST,
      port: 5432,
      username: process.env.DB_USER,
      password: process.env.DB_PASS,
      database: process.env.DB_NAME,
      autoLoadEntities: true,
      synchronize: false, // use migrations in production
    }),
  ],
})
export class AppModule {}

3. Define an entity

// user.entity.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ unique: true })
  email: string;
}

4. Inject and use the repository

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

  create(email: string) {
    return this.repo.save(this.repo.create({ email }));
  }
}

FAQ

Should I use synchronize: true?

Only in development. In production set synchronize: false and manage the schema with TypeORM migrations so deployments are predictable.

TypeORM or Prisma for NestJS?

Both work. TypeORM has first-class NestJS integration and decorators; Prisma offers a type-safe query client. Pick based on whether you prefer decorator-based entities or a schema-first approach.

← All guides