Skip to content

Connecting to PostgreSQL using Node.js

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.

  • 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

Section titled “Steps to Connect to PostgreSQL Using Node.js”
  1. Log in to your hosting account via SSH.

  2. Ensure Node.js is installed.

  3. Install the pg package:

    Terminal window
    npm install pg
// Import the pg module
import pg from 'pg';
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();
  • 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..