'cannot connect an SSL secured database to typeorm

This is my first time using NestJS and I am having trouble connecting my Postgres database which is hosted on Digitalocean to NestJS.

I searched online for solutions and tried adding "ssl": "true" or "extra": { "ssl": "true" }

Heres my ormconfig.json

{
  "type": "postgres",
  "host": "host",
  "port": "port",
  "username": "username",
  "password": "password",
  "database": "database",
  "extra": {
    "ssl": "true"
  },
  "synchronize": "true",
  "logging": "true",
  "entities": ["src/**/*.entity.ts", "dist/**/*.entity.js"]
}

I expect it to connect to the server. The error I'm getting is [TypeOrmModule] Unable to connect to the database. error: no pg_hba.conf entry for host "", user "", database "", SSL off



Solution 1:[1]

This works if you are connecting to postgres database on heroku from localhost using typeorm.

ormconfig.json

{
  "name": "default",
  "type": "postgres",
  "url": "postgres://username:password@host:port/database",
  "synchronize": true,
  "logging": true,
  "entities": ["src/entity/*.*"],
  "ssl": true,
  "extra": {
    "ssl": {
      "rejectUnauthorized": false
    }
  }
}

Solution 2:[2]

This is my NestJS TypeORM config on Heroku:

TypeOrmModule.forRoot({
  type: 'postgres',
  url: process.env.DATABASE_URL,
  autoLoadEntities: true,
  ssl:
    process.env.NODE_ENV === 'production'
      ? { rejectUnauthorized: false }
      : false,
}),

The SSL option is mandatory as described here: https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js

Solution 3:[3]

  ssl: {
    rejectUnauthorized: false,
    ca: fs.readFileSync('/path/to/server-certificates/root.crt').toString(),
    key: fs.readFileSync('/path/to/client-key/postgresql.key').toString(),
    cert: fs.readFileSync('/path/to/client-certificates/postgresql.crt').toString(),
  },

via https://node-postgres.com/features/ssl

Solution 4:[4]

You can set the PQSSLMODE environment variable to require - libpq will read those automatically, if not set otherwise, and establish a secure connection.

See also: https://www.postgresql.org/docs/current/libpq-envars.html

Solution 5:[5]

Add this line to your config settings:

options: { encrypt: false }

Your configuration should look something like this:

TypeOrmModule.forRoot({
  type: 'mssql',
  host: 'your_db_server_address',
  port: 1433,
  username: 'user',
  password: 'pwd',
  database: 'your_db_name_here',
  entities: [Subscription],
  options: { encrypt: false }
  
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 noor
Solution 2 thisismydesign
Solution 3 BKH
Solution 4 Laura
Solution 5 Kazi