I had trouble connecting to digitalocean database in node js and was getting errors such as:

Error: self signed certificate in certificate chain.

or

error: no pg_hba.conf entry for host "x.x.x.x", user "------", database "------", SSL off

but then I added ca-certificate.crt file into my node.js app newly created ssl folder and wrote this

const pg = require('pg')
const fs = require('fs')

const pool = new pg.Pool({
    user: "-----",
    password: "--------",
    host: "-----------",
    port: 25060,
    database: "----",
    ssl: true,
    ssl: {
      ca: fs.readFileSync('../ssl/ca-certificate.crt'),
      rejectUnauthorized: true,
    }

module.exports = pool;

This line fixed all those errors and now I can connect to the database

ca: fs.readFileSync('../ssl/ca-certificate.crt'),

but I feel it’s not very common practice to have ca-certificate.crt file in my app folder so I would like to know how to handle this?

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
2 answers

Hi there @beuu,

I have not tested this with NodeJS, but I’ve done it with other frameworks and PostgreSQL. What you can do is to add the certificate at:

~/.postgresql/root.crt

Then make sure that the file has secure permissions:

  • chmod 600 ~/.postgresql/root.crt

That way the connection to your PostgreSQL server would default to using that certificate.

Let me know how it goes!
Regards,
Bobby

The certificates should be put in a folder dedicated to certificates and key files. An example location would be /usr/local/ssl/crt/. All of your certificates need to be in the same folder. Save the changes to the file once you are finished.

Submit an Answer