Build a Hello World App with CockroachDB and the node-postgres Driver

This tutorial shows you how build a simple Hello World Node.js application with CockroachDB and the node-postgres driver.

Step 1. Start CockroachDB

Create a free cluster

  1. If you haven't already, sign up for a CockroachDB Cloud account.
  2. Log in to your CockroachDB Cloud account.
  3. On the Clusters page, click Create Cluster.
  4. On the Create your cluster page, select CockroachDB Serverless.

    Note:

    This cluster will be free forever.

  5. Click Create your free cluster.

Your cluster will be created in approximately 20-30 seconds.

Set up your cluster connection

  1. Navigate to the cluster's SQL Users page, and create a new user, with a new password.

  2. Navigate to the Cluster Overview page, select Connect, and, under the Connection String tab, download the cluster certificate.

  3. Take note of the connection string provided. You'll use it to connect to the database later in this tutorial.

  1. If you haven't already, download the CockroachDB binary.
  2. Run the cockroach start-single-node command:

    icon/buttons/copy
    $ cockroach start-single-node --advertise-addr 'localhost' --insecure
    

    This starts an insecure, single-node cluster.

  3. Take note of the following connection information in the SQL shell welcome text:

    CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s)
    build:               CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11)
    webui:               http://localhost:8080
    sql:                 postgresql://root@localhost:26257?sslmode=disable
    

    You'll use the sql connection string to connect to the cluster later in this tutorial.

Warning:

The --insecure flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead.

Step 2. Get the code

Clone the code's GitHub repo:

icon/buttons/copy
$ git clone https://github.com/cockroachlabs/hello-world-node-postgres/

The app.js file contains all of the code for the sample Hello World app:

icon/buttons/copy
const parse = require("pg-connection-string").parse;
const { Client } = require("pg");
const prompt = require("prompt");

(async () => {

  prompt.start()
  const URI = await prompt.get("connectionString");
  var connectionString;
  // Expand $env:appdata environment variable in Windows connection string
  if (URI.connectionString.includes("env:appdata")) {
    connectionString = await URI.connectionString.replace(
      "$env:appdata",
      process.env.APPDATA
    );
  }
  // Expand $HOME environment variable in UNIX connection string
  else if (URI.connectionString.includes("HOME")) {
    connectionString = await URI.connectionString.replace(
      "$HOME",
      process.env.HOME
    );
  }
  var config = parse(connectionString);
  config.port = 26257;
  config.database = 'defaultdb';
  const client = new Client(config);

  // Connect to database
  try {
    await client.connect();
    console.log("Hey! You successfully connected to your CockroachDB cluster.")
  } catch (err) {
    console.log(`error connecting: ${err}`)
  }

  // Exit program
  process.exit();
})().catch((err) => console.log(err.stack));

This program does the following:

  1. Attempts to connect to a running cluster, given a connection string.
  2. Prints a message to the terminal about the connection status.

Step 3. Run the code

Initialize and run the app:

icon/buttons/copy
$ npm install
icon/buttons/copy
$ node app.js

The program will prompt you for a connection string to the database:

prompt: connectionString:

Enter postgresql://root@localhost:26257?sslmode=disable (the sql connection URL provided in the cockroach welcome text).

Enter the connection string provided in the Connection info window of the CockroachDB Cloud Console.

Note:

You need to provide a SQL user password in order to securely connect to a CockroachDB Cloud cluster. The connection string should have a placeholder for the password (<ENTER-PASSWORD>).

After entering the connection string, the program will execute.

The output should look like this:

Hey! You successfully connected to your CockroachDB cluster.

See also

You might also be interested in the following pages:

YesYes NoNo