Search code examples
databasepostgresqlherokunestjstypeorm

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


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: '...',
    }),
  ],
})

Solution

  • 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