Search code examples
postgresqlnestjstypeorm

NestJS [TypeOrmModule] Unable to connect to the database


I want to connect to a remote PostgreSQL database (which is being hosted on Heroku) and getting this error:

error: no pg_hba.conf entry for host "<My public IP address>", user "<username>", database "<dbname>", SSL off

Here's my app.module.ts

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

const cfg: TypeOrmModuleOptions = {
  type: 'postgres',
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  username: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  port: Number(process.env.DB_PORT),
};

@Module({
  imports: [TypeOrmModule.forRoot(cfg)],
})
export class AppModule {}

Every DB_* variable matches corresponding values in Heroku's Database Credentials

I think that the problem is somewhere in TypeORM, because connecting to the same DB with the same .env file values worked in my other application (written in different programming language)

Any ideas on what could be wrong?


Solution

  • To fix the problem, i had to add these lines in my cfg object:

    ssl: true,
    extra: {
      ssl: {
        rejectUnauthorized: false,
      },
    },
    

    With the ssl: true option we will have to use SSL cert, which we don't have yet.

    The ideal solution is to get a new SSL certificate, but for development this should be enough.