How to create a pool object in javascript that can connect to a database backend using SSL?

I followed a guide on how to create a Node JS backend on PostgreSQL and a ReactJS frontend, which is working well, see here for more.

The js pool object of the quide looks as follows:

const Pool = require('pg').Pool
const pool = new Pool({
  user: 'my_user',
  host: 'localhost',
  database: 'my_database',
  password: 'postgres',
  port: 5432,
});

I tried doing the same with a PostgreSQL Webserver using SSL encryption. This question is not tagged postgresql since the pool looks the same for mysql and other databases. It is also not tagged Linux since it should work the same on other OS.

How to create a pool object from the Pool class in javascript that can connect to a PostgreSQL backend using SSL?

Answer

You need to save the certificate, call it server-certificate.pem, in a place with a static path starting with / (~ for your user’s home directory does not work). Therefore, you need to move it to a static place.

I copied the file to a newly created directory certificates, but that is of course up to you. You will need super user rights for this.

/etc/certificates/server-certificate.pem

You need to load fs and use it in the SSL part, see How to establish a secure connection (SSL) from a Node.js API to an AWS RDS.

const Pool = require('pg').Pool
const fs = require('fs');
const pool = new Pool({
  user: 'my_user',
  host: 'my_host',
  database: 'my_database',
  password: 'my_password',
  port: 22222,
  ssl: {
    ca: fs
      .readFileSync("/etc/certificates/server-certificate.pem")
      .toString()
  }
});