How to configure NestJS TypeOrm with URI instead of host, port, username and password fields?

Viewed 1079

The Heroku Postgres addon provides DB connection details as postgres://user:pw@host:port in the DATABASE_URL env var.

I'm wondering how to configure a NestJS app using TypeOrm, because all the examples look like this:

@Module({
  imports: [
    TypeOrmModule.forRoot({
        type: 'postgres',
        host: '...',
        port: 5432,
        username: '...',
        password: '...',
    }),
  ],
})
1 Answers

You can use the url option:

TypeOrmModule.forRoot({
  type: 'postgres',
  url: process.env.DATABASE_URL,
}),

You can also do this locally, for example, on Docker using the postgres image your connection looks like this:

postgres://postgres:@<db_service_name>:5432
Related