How to connect to PostgreSQL using Node.js

This article describes how to connect to a PostgreSQL database using Node.js.

  • Node.js must already be installed on your account. For information about how to install Node.js, please see this article.
  • The PostgreSQL databases and users must already exist before you can use the code sample below. For information about how to manage PostgreSQL databases using cPanel, please see this article.

Connecting to PostgreSQL using Node.js

The node-postgres package includes all of the functionality you need to access and work with PostgreSQL databases in Node.js. Before you can do this, however, you must install the node-postgres package on your account. To do this, follow these steps:

  1. Log in to your account using SSH.
  2. Type the following commands:
    cd ~
    npm install pg
    
Code sample

After you install the node-postgres package, you are ready to work with PostgreSQL databases and manipulate data in them. The following sample Node.js code demonstrates how to do this.

In your own code, replace dbname with the database name, username with the PostgreSQL database username, and password with the database user's password. Additionally, you should modify the SELECT query to match a table in your own database:

import pg from 'pg';

const { Client } = pg;
const client = new Client({
    host: 'localhost',
    database: 'dbname',
    user: 'username',
    password: 'password',
});

await client.connect();
 
const res = await client.query('SELECT fname, lname FROM employee');
console.log(res.rows[0]);
await client.end();

In this example, we first instantiate a Client object that specifies a connection to a PostgreSQL database.

After we call the connect() method on the client object, we can run raw SQL statements such as SELECT.

Finally, we call the end() method to close the client's connection to the database.

You may receive the following error message when you try to run this code:

SyntaxError: Cannot use import statement outside a module

If you receive this error message, create a package.json file in the same directory as the code file. Copy the following text and then paste it into the package.json file:

{
    "type": "module"
}

The code should now run.

More Information

For more information about the node-postgres package, please visit https://node-postgres.com/.

Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.

We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.