# Connecting to PostgreSQL using Node.js

> Connect a Node.js application to PostgreSQL with the node-postgres (pg) package and handle common connection errors.

Source: https://helpcenter.ruachost.com/developers/databases/connecting-to-postgresql-using-node-js/

> **PostgreSQL is available on Managed VPS only:**
Ruachost shared hosting supports MySQL (MariaDB) databases, not PostgreSQL. To use PostgreSQL, choose a [Managed VPS](https://ruachost.com/vps).

Node.js  applications can interact with PostgreSQL databases using the **node‑postgres (pg)** package. On **ruachost.com**, you can use this library to establish connections, run queries, and manage your data directly from your Node.js  code.

## Why Use Node.js for PostgreSQL?

- Asynchronous I/O makes queries fast and scalable.
- Widely supported library (`pg`) with robust features.
- Perfect for modern web applications and APIs.

## Steps to Connect to PostgreSQL Using Node.js

### Step 1: Install Node.js and `pg`

1. Log in to your hosting account via SSH.
2. Ensure Node.js  is installed.
3. Install the `pg` package:

   ```bash
   npm install pg
   ```

### Step 2: Write Connection Code

### Example

```
// Import the pg module

const { Client } = pg;

// Configure connection
const client = new Client({
  host: 'localhost',
  database: 'yourdbname',
  user: 'yourusername',
  password: 'yourpassword',
  port: 5432
});

// Connect to PostgreSQL
await client.connect();

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

// Close connection
await client.end();
```

### Step 3: Handle Common Errors

- If you see:

  ```
  SyntaxError: Cannot use import statement outside a module
  ```

  → Create a `package.json` file in your project directory and add:

  ```
  {
    "type": "module"
  }
  ```
- This enables ES module syntax (`import`) in Node.js..

> **Important Notes:**
- Replace `localhost`, `yourdbname`, `yourusername`, and `yourpassword` with actual database credentials.
- Ensure PostgreSQL databases and users are already created before connecting.
- Always close connections (`client.end()`) to free resources.
- Use prepared statements for secure queries against SQL injection.
