Javascript & Typescript

Connecting with Javascript & Typescript

Javascript (and subsequently Typescript) has a NPM package called "pg". Many other Javascript libraries use this library for their underlying connection. For instance, there area two libraries called "sequelize" and another one called "Postgres". Both of them use "pg" under the hood, so the connection methods are similar.

If you are using Prisma, we have a specific tutorial for Javascript with Prisma.

If you are using Sequelize, we have a specific tutorial for Javascript with Sequelize.

TL;DR:

The #1 question we have with Node is related to the self-signed SSL certificates used by Crunchy Bridge. The typical error looks like this:

"name":"PostgresError","message":"no pg_hba.conf entry for host \"127.0.0.1\",
user \"application\", database \"my-db\", no encryption"

There are two options here:

Disabling certificate verification is slightly messy in node-postgres. Set rejectUnauthorized: false and do not add any ssl arguments to the connection string. Here's an example:

const client = new Client({
  connectionString: 'postgres://user:password@host:port/db',
  ssl: {
    require: true, // this line is not necessary, but it's good to be explicit
    rejectUnauthorized: false,
  },
})

Now, for the complete walkthrough.

Create your Crunchy Bridge Postgres cluster

Creating a Crunchy Bridge cluster is pretty simple. Log into your Crunchy Bridge account, and click “Create Cluster”, then follow the cluster create form.

From here, we’ll want to get a “connection string” that we can use later. It looks like this:

postgres://user:password@host:port/database?setting=value

Once your Postgres cluster has a status of “ready” (a few minutes), click on the “Connections” tab for your connection string.

We will set this value as a DATABASE_URL value later when connecting to the database.

Preparation

For this tutorial, first create a project directory. Then, run the following commands while within that directory.

Installing pg package

Run the following to install the "pg" package:

bash> npm install pg

Connecting to Postgres

Create a file called db-test.js, and add the following content to it:

const { Client } = require('pg')
const client = new Client({
  connectionString: process.env.DATABASE_URL,
  ssl: {
    require: true,
    rejectUnauthorized: false,
  },
})
await client.connect()

const res = await client.query('SELECT $1::text as message', ['Hello world!'])
console.log(res.rows[0].message) // Hello world!
await client.end()

Then, run the following from bash:

bash> DATABASE_URL=<connection string from above> node db-test.js

By prefixing the command with the DATABASE_URL, it passes the value as an environmental variable. Then, the application code picks up the DATABASE_URL with process.env.DATABASE_URL.