Skip to main content

Connect with NodeJS Early availability

Connect to an Aiven for AlloyDB Omni database from NodeJS, using the pg package.

Prerequisites

Connect to a service

  1. Create a file named index.js with the following content:

    const fs = require("fs");
    const pg = require("pg");

    const config = {
    user: "USER",
    password: "PASSWORD",
    host: "HOST",
    port: "PORT",
    database: "DATABASE",
    ssl: {
    rejectUnauthorized: true,
    ca: fs.readFileSync("./ca.pem").toString(),
    },
    };

    const client = new pg.Client(config);
    client.connect(function (err) {
    if (err) throw err;
    client.query("SELECT VERSION()", [], function (err, result) {
    if (err) throw err;

    console.log(result.rows[0]);
    client.end(function (err) {
    if (err) throw err;
    });
    });
    });

    Replace the connection parameters with the values available on the Overview page in the Aiven Console:

    VariableDescription
    USERAiven for AlloyDB Omni service username
    PASSWORDAiven for AlloyDB Omni service password
    HOSTHostname for Aiven for AlloyDB Omni service connection
    PORTPort for Aiven for AlloyDB Omni service connection
    DATABASEDatabase name for Aiven for AlloyDB Omni service connection

    This code opens a connection to the database, runs a query checking the database version, and prints the response.

  2. Run the code:

    node index.js

Expect output like:

PostgreSQL 15.5 on x86_64-pc-linux-gnu, compiled by [...]