SSL for PostgreSQL connection nodejs
You can achieve this like this:
postgres://user:pass@host:port/database?ssl=true
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!
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()});