> ## Documentation Index
> Fetch the complete documentation index at: https://kb.hosting.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Connecting to PostgreSQL using Node.js

> Learn how to connect to a PostgreSQL database using Node.js. This article includes sample code you can use in your own sites.

<Tip>
  * Node.js must already be installed on your account. For information about how to install Node.js, please see \[installing node.js [this article](/docs/installing-and-configuring-nodejs-on-managed-hosting).
  * 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](/docs/managing-postgresql-databases).
</Tip>

## Connecting to PostgreSQL using Node.js

The [**node-postgres** package](https://node-postgres.com/) 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](/docs/using-ssh-secure-shell).
2. Type the following commands:

   ```shell theme={null}
   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:

```javascript theme={null}
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:

```json theme={null}
{
    "type": "module"
}
```

The code should now run.

## More information

For more information about the **node-postgres** package, please visit [https://node-postgres.com/](https://node-postgres.com/).
