# Connecting with Node.js

This guide explains how to establish a connection between a Node.js application and a PostgreSQL database using the `pg` package. It walks through the necessary setup, configuration, and execution of a simple SQL query.

## **Variables**

Certain parameters must be provided to establish a successful connection to a PostgreSQL database. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="border-collapse: collapse; width: 100%; height: 178.781px;"><colgroup><col style="width: 16.329%;"></col><col style="width: 41.8355%;"></col><col style="width: 41.8355%;"></col></colgroup><thead><tr style="height: 29.7969px;"><td style="height: 29.7969px;">**Variable**  
</td><td style="height: 29.7969px;">**Description**  
</td><td>**Purpose**</td></tr></thead><tbody><tr style="height: 29.7969px;"><td style="height: 29.7969px;">`USER`</td><td style="height: 29.7969px;">PostgreSQL username, from the Elestio service overview page</td><td>Identifies the database user who has permission to access the PostgreSQL database.</td></tr><tr style="height: 29.7969px;"><td style="height: 29.7969px;">`PASSWORD`</td><td style="height: 29.7969px;">PostgreSQL password, from the Elestio service overview page</td><td>The authentication key required for the specified `USER` to access the database</td></tr><tr style="height: 29.7969px;"><td style="height: 29.7969px;">`HOST`</td><td style="height: 29.7969px;">Hostname for PostgreSQL connection, from the Elestio service overview page</td><td>The address of the server hosting the PostgreSQL database.</td></tr><tr style="height: 29.7969px;"><td style="height: 29.7969px;">`PORT`</td><td style="height: 29.7969px;">Port for PostgreSQL connection, from the Elestio service overview page</td><td>The network port is used to connect to PostgreSQL. The default port is `5432`.</td></tr><tr style="height: 29.7969px;"><td style="height: 29.7969px;">`DATABASE`</td><td style="height: 29.7969px;">Database Name for PostgreSQL connection, from the Elestio service overview page</td><td>The name of the database being accessed. A PostgreSQL instance can contain multiple databases.</td></tr></tbody></table>

These values can usually be found in the Elestio service overview details as shown in the image below, make sure to take a copy of these details and add it to the code moving ahead.

[![Screenshot 2025-03-20 at 12.34.30 PM.jpg](https://docs.elest.io/uploads/images/gallery/2025-03/scaled-1680-/screenshot-2025-03-20-at-12-34-30-pm.jpg)](https://docs.elest.io/uploads/images/gallery/2025-03/screenshot-2025-03-20-at-12-34-30-pm.jpg)

## **Prerequisites**

- **Install Node.js and NPM**
    
    
    - Check if Node.js is installed by running: <div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary"><div class="sticky top-9"></div><div class="overflow-y-auto p-4" dir="ltr">`node -v`</div></div>
    - If not installed, download it from [nodejs.org](https://nodejs.org/) and install.
    - Verify npm installation: <div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary"><div class="sticky top-9"></div><div class="overflow-y-auto p-4" dir="ltr">`npm -v`</div></div>
- **Install the `pg` Package**  
    The `pg` package enables Node.js applications to interact with PostgreSQL. Install it using:
    
    <div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary"><div class="sticky top-9"></div><div class="overflow-y-auto p-4" dir="ltr">`npm install pg --save`</div></div>

## **Code**

Once all prerequisites are set up, create a new file named `pg.js` and add the following code:

```javascript
const pg = require("pg"); 

// Database connection configuration
const config = {
  user: "USER", 
  password: "PASSWORD",
  host: "HOST",
  port: "PORT",
  database: "DATABASE",
};

// Create a new PostgreSQL client
const client = new pg.Client(config);

// Connect to the database
client.connect((err) => {
  if (err) {
    console.error("Connection failed:", err);
    return;
  }
  console.log("Connected to PostgreSQL");

  // Run a test query to check the PostgreSQL version
  client.query("SELECT VERSION()", [], (err, result) => {
    if (err) {
      console.error("Query execution failed:", err);
      client.end();
      return;
    }

    console.log("PostgreSQL Version:", result.rows[0]);

    // Close the database connection
    client.end((err) => {
      if (err) console.error("Error closing connection:", err);
    });
  });
});

```

To execute the script, open the terminal or command prompt and navigate to the directory where `pg.js`. Once in the correct directory, run the script with the command

```bash
node pg.js
```

If the connection is successful, the terminal will display output similar to:

```bash
Connected to PostgreSQL
PostgreSQL Version: {
  version: 'PostgreSQL 16.8 (Debian 16.8-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit'
}
```