SSL for PostgreSQL connection nodejs

I am trying to connect to my Heroku PostgreSQL DB and I keep getting an SSL error. Does anyone have an idea on how to enable SSL in the connection string?

postgres://user:pass@host:port/database;

Been looking for it everywhere but it does not seem to be a very popular topic. By the way, I am running Nodejs and the node-pg module with its connection-pooled method:

pg.connect(connString, function(err, client, done) {
  // Should work.
});

Comments are much appreciated.


Solution 1:

You can achieve this like this:

postgres://user:pass@host:port/database?ssl=true

Solution 2:

You also can use this code below when create a new Client from node-postgres:

var pg = require("pg");

var client = new pg.Client({
  user: "yourUser",
  password: "yourPass",
  database: "yourDatabase",
  port: 5432,
  host: "host.com",
  ssl: true
});

client.connect();

var query = client.query('CREATE TABLE people(id SERIAL PRIMARY KEY, name VARCHAR(100) not null)');

query.on('row', function(row) {
  console.log(row.name);
});

query.on('end', client.end.bind(client));

Hope this helps!

Solution 3:

With Google Cloud PG and pg-promise I had a similar need. The error I got (using ?ssl=true) was connection requires a valid client certificate.

SSL connection is not documented for pg-promise but it is built on node-postgres. As explained in the link, the ssl config parameter can be more than just true:

const pgp = require('pg-promise')();
const fs = require('fs');

const connectionConf = {
    host: 'myhost.com',
    port: 5432,
    database: 'specific_db_name',
    user: 'my_App_user',
    password: 'aSecretePass',
    ssl: {
        rejectUnauthorized : false,
        ca   : fs.readFileSync("server-ca.pem").toString(),
        key  : fs.readFileSync("client-key.pem").toString(),
        cert : fs.readFileSync("client-cert.pem").toString(),
  }

};
const new_db = pgp(connectionConf);
new_db.any('SELECT * FROM interesting_table_a LIMIT 10')
    .then(res => {console.log(res);})
    .catch(err => {console.error(err);})
    .then(() => {new_db.$pool.end()});

Solution 4:

For anybody looking for a TypeORM solution, it's also {ssl: true}.

Full example:

const connectionOptions: PostgresConnectionOptions = {
    name: `default`,
    type: `postgres`,
    url: process.env.DATABASE_URL,
    ssl: process.env.DATABASE_SSL === `true`
}