Here is an example I used to connect node.js to my Postgres database.

The interface in node.js that I used can be found here https://github.com/brianc/node-postgres

var pg = require('pg');
var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";

var client = new pg.Client(conString);
client.connect();

//queries are queued and executed one after another once the connection becomes available
var x = 1000;

while (x > 0) {
    client.query("INSERT INTO junk(name, a_number) values('Ted',12)");
    client.query("INSERT INTO junk(name, a_number) values(2)", ['John', x]);
    x = x - 1;
}

var query = client.query("SELECT * FROM junk");
//fired after last row is emitted

query.on('row', function(row) {
    console.log(row);
});

query.on('end', function() {
    client.end();
});



//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text, (optional) parameter values, and (optional) query name
client.query({
    name: 'insert beatle',
    text: "INSERT INTO beatles(name, height, birthday) values(2, $3)",
    values: ['George', 70, new Date(1946, 02, 14)]
});

//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
client.query({
    name: 'insert beatle',
    values: ['Paul', 63, new Date(1945, 04, 03)]
});
var query = client.query("SELECT * FROM beatles WHERE name = $1", ['john']);

//can stream row results back 1 at a time
query.on('row', function(row) {
    console.log(row);
    console.log("Beatle name: %s", row.name); //Beatle name: John
    console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
    console.log("Beatle height: %d' %d\"", Math.floor(row.height / 12), row.height % 12); //integers are returned as javascript ints
});

//fired after last row is emitted
query.on('end', function() {
    client.end();
});

UPDATE:- THE query.on function is now deprecated and hence the above code will not work as intended. As a solution for this look at:- query.on is not a function

Answer from Kuberchaun on Stack Overflow
Top answer
1 of 8
326

Here is an example I used to connect node.js to my Postgres database.

The interface in node.js that I used can be found here https://github.com/brianc/node-postgres

var pg = require('pg');
var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";

var client = new pg.Client(conString);
client.connect();

//queries are queued and executed one after another once the connection becomes available
var x = 1000;

while (x > 0) {
    client.query("INSERT INTO junk(name, a_number) values('Ted',12)");
    client.query("INSERT INTO junk(name, a_number) values(2)", ['John', x]);
    x = x - 1;
}

var query = client.query("SELECT * FROM junk");
//fired after last row is emitted

query.on('row', function(row) {
    console.log(row);
});

query.on('end', function() {
    client.end();
});



//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text, (optional) parameter values, and (optional) query name
client.query({
    name: 'insert beatle',
    text: "INSERT INTO beatles(name, height, birthday) values(2, $3)",
    values: ['George', 70, new Date(1946, 02, 14)]
});

//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
client.query({
    name: 'insert beatle',
    values: ['Paul', 63, new Date(1945, 04, 03)]
});
var query = client.query("SELECT * FROM beatles WHERE name = $1", ['john']);

//can stream row results back 1 at a time
query.on('row', function(row) {
    console.log(row);
    console.log("Beatle name: %s", row.name); //Beatle name: John
    console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
    console.log("Beatle height: %d' %d\"", Math.floor(row.height / 12), row.height % 12); //integers are returned as javascript ints
});

//fired after last row is emitted
query.on('end', function() {
    client.end();
});

UPDATE:- THE query.on function is now deprecated and hence the above code will not work as intended. As a solution for this look at:- query.on is not a function

2 of 8
37

A modern and simple approach: pg-promise:

const pgp = require('pg-promise')(/* initialization options */);

const cn = {
    host: 'localhost', // server name or IP address;
    port: 5432,
    database: 'myDatabase',
    user: 'myUser',
    password: 'myPassword'
};

// alternative:
// var cn = 'postgres://username:password@host:port/database';

const db = pgp(cn); // database instance;

// select and return a single user name from id:
db.one('SELECT name FROM users WHERE id = $1', [123])
    .then(user => {
        console.log(user.name); // print user name;
    })
    .catch(error => {
        console.log(error); // print the error;
    });

// alternative - new ES7 syntax with 'await':
// await db.one('SELECT name FROM users WHERE id = $1', [123]);

See also: How to correctly declare your database module.

🌐
node-postgres
node-postgres.com › features › connecting
node-postgres
5 days ago - node-postgres uses the same environment variables as libpq and psql to connect to a PostgreSQL server. Both individual clients & pools will use these environment variables. Here’s a tiny program connecting node.js to the PostgreSQL server:
Discussions

cant connect with postgresql with nodejs
If I had to guess, wrong password ? More on reddit.com
🌐 r/node
20
4
May 5, 2018
Does node.js and Postgres not go together or something?
I use it all the time and it's great. Simply use node-postgres (pg), it has a good documentation. ORM is not necessary imho. More on reddit.com
🌐 r/node
127
68
May 6, 2019
Advice for using postgresql with node?

Ive been using sequelize for the last few years and have found it to be rock solid and really easy to use (it was a little sketchy and unstable before v2.x, but all is good now). Features that Ive really liked about it that either dont exist, or arent as nice to use (IMO) in other frameworks include:

  • Relationship eager loading (i.e. joins via the ORM)

  • Transactions can be included everywhere

  • Support for not only the JSONB type, but actually querying it

  • Migration support (via sequelize-cli)

  • Everything is promise based

Do you guys put node controllers + models and postgres in their own server, apart from the node.js server??

All of the node apps Im running currently are in containers, so theyre on different physical machines than Postgres which lives on its own dedicated machine.

More on reddit.com
🌐 r/node
13
8
June 7, 2016
Has anyone had success connecting Node.js / Express with PostgreSQL?

Relational databases are the last thing that can have outdated information. The basic principles have remained the same for ages. The question that you're asking is so easy to google..

More on reddit.com
🌐 r/webdev
13
0
July 17, 2018
🌐
This Dot Labs
thisdot.co › blog › connecting-to-postgresql-with-node-js
Connecting to PostgreSQL with Node.js - This Dot Labs
February 14, 2023 - You can use a connection pool or just instantiate a client. Here, we create both using credentials inside of the code itself. You can also configure connections with environment variables instead! This is an example index.js file that I put into a project I generated with npm init and installed node-postgres into:
🌐
Holt
sql.holt.courses › lessons › data › nodejs-and-postgresql
Node.js and PostgreSQL – Complete Intro to SQL
You can think of a client as an individual connection you open and then eventually close to your PostgreSQL database. When you call connect on a client, it handshakes with the server and opens a connection for you to start using.
🌐
ScaleGrid
scalegrid.io › blog › how-to-connect-postgresql-database-in-node-js
How To Connect PostgreSQL Database In Node.Js | ScaleGrid
December 17, 2023 - In the example above, you need to replace connection information ‘your_username’, ‘your_host’, ‘your_database’, ‘your_password’, and ‘your_port’ with the appropriate values for your PostgreSQL database and host configuration. This will allow you to connect Node js to your ...
🌐
Northflank
northflank.com › guides › connecting-to-a-postgresql-database-using-node-js
Connecting to a PostgreSQL database using Node.js — Northflank
November 25, 2021 - In this example, a simple query which returns the input is run and printed to the console. In the end the client.end() method is called to terminate the database connection properly.
🌐
OVHcloud
ovhcloud.com › home › tutorials › how to access a postgresql from node.js application
How to access a PostgreSQL from Node.js application? | OVHcloud Worldwide
Use `npm install ` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (nodejs-pg-example) version: (1.0.0) description: Example project to access PostgreSQL from a Node.js application entry point: (index.js) test command: git repository: keywords: author: OVHcloud license: (ISC) About to write to /home/ubuntu/nodejs-pg-example/package.json: { "name": "nodejs-pg-example", "version": "1.0.0", "description": "Example project to access PostgreSQL from a Node.js application", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "OVHcloud", "license": "ISC" } Is this OK?
Find elsewhere
🌐
Medium
medium.com › @fanbubu0 › connecting-to-postgresql-database-in-node-js-a-step-by-step-guide-d364a8c7a51c
“Connecting to PostgreSQL Database in Node.js: A Step-by-Step Guide | by William El France | Medium
January 16, 2024 - Let’s dive into the step-by-step ... applications. ... const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'giant-mart', password: 'postgres', port: 5432, idleTimeoutMillis: 300 });...
🌐
MakeUseOf
makeuseof.com › home › programming › how to connect to a postgresql database using node.js
How to Connect to a PostgreSQL Database Using Node.js
June 21, 2022 - PGUSER=<PGUSER> \ PGHOST=<PGHOST> \ PGPASSWORD=<PGPASSWORD> \ PGDATABASE=<PGDATABASE> \ PGPORT=<PGPORT> \ node index.js · Connecting Node to PostgreSQL like this allows you to write a more reusable program.
🌐
YouTube
youtube.com › kindson the tech pro
How to Connect Node js to PostgreSQL Database and Fetch data - YouTube
This video explains how to connect Node.js to PostgreSQL database and fetch data step by stepNode.js Tutorials Steps - https://www.kindsonthegenius.com/nodej...
Published   April 24, 2021
Views   220K
🌐
Medium
medium.com › @izhekka › connecting-postgresql-with-node-js-f3e7d41a7537
Connecting PostgreSQL with Node.JS | by Yauheni Dzenisenka | Medium
May 1, 2025 - For this integration, we will be using the pg library which is a non-blocking PostgreSQL client for Node.JS and supports pure JavaScript as well as TypeScript. The full code example is available in my GihHub repo. The project includes the Node.JS server implemented with Express and a Docker Compose configuration to run the PostgreSQL database locally with a single command line command.
🌐
LogRocket
blog.logrocket.com › home › crud rest api with node.js, express, and postgresql
CRUD REST API with Node.js, Express, and PostgreSQL - LogRocket Blog
March 27, 2026 - Alternatively, install nodemon (npm install -D nodemon) and run npx nodemon index.js for a slightly richer experience with colored output and custom ignore rules. Go to http://localhost:3000 in the URL bar of your browser, and you’ll see the JSON we set earlier: ... The Express server is running now, but it’s only sending some static JSON data that we created. The next step is to connect to PostgreSQL from Node.js to be able to make dynamic queries.
🌐
Medium
jelastic.medium.com › how-to-connect-postgresql-with-node-js-application-dbdff08c9474
How to Connect PostgreSQL with Node.js Application | by Jelastic | Medium
June 19, 2020 - The node-postgres supports client and pool connections. A client is one static connection and the pool manages the dynamic list of client objects with the automatic reconnection function. We’ll go with the pool option that can be used in case of having or expecting several simultaneous requests. So, create a file with the .js extension, using any text editor of your choice (e.g.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-postgresql-with-node-js-on-ubuntu-20-04
How To Use PostgreSQL With Node.js on Ubuntu 20.04 | DigitalOcean
November 30, 2021 - Once you login into the shell, you’ll create a table for the Node.js app. To open the shell as the fish_user, enter the following command: ... sudo -u fish_user switches your Ubuntu user to fish_user and then runs the psql command as that user. The -d flag specifies the database you want ...
🌐
Aiven
aiven.io › aiven for postgresql® › connection methods › nodejs
Connect to Aiven for PostgreSQL® with NodeJS | Aiven docs
const fs = require("fs"); const pg = require("pg"); const config = { user: "USER", password: "PASSWORD", host: "HOST", port: "PORT", database: "DATABASE", ssl: { rejectUnauthorized: true, ca: fs.readFileSync("./ca.pem").toString(), }, }; const client = new pg.Client(config); client.connect(function (err) { if (err) throw err; client.query("SELECT VERSION()", [], function (err, result) { if (err) throw err; console.log(result.rows[0]); client.end(function (err) { if (err) throw err; }); }); }); This code creates a PostgreSQL client and opens a connection to the database.
🌐
DEV Community
dev.to › thisdotmedia › connecting-to-postgresql-with-node-js-k6k
Connecting to PostgreSQL with Node.js - DEV Community
June 25, 2024 - You can use a connection pool or just instantiate a client. Here, we create both using credentials inside of the code itself. You can also configure connections with environment variables instead! This is an example index.js file that I put into a project I generated with npm init and installed node-postgres into:
🌐
DEV Community
dev.to › aguowisdom › connecting-to-a-postgresql-database-with-nodejs-a-step-by-step-guide-n6j
CONNECTING TO A POSTGRESQL DATABASE WITH NODE.JS: A STEP-BY-STEP GUIDE - DEV Community
September 3, 2023 - This will install the latest versions of each package and add them to your project's node_modules directory. ... Before we can connect to our PostgreSQL database, we need to create a new database in the psql terminal. Open your terminal and enter the following command: ... Replace your_database_name with a name for your database. This will create a new database with the specified name. Now that we have a database set up, let's create the necessary files to connect to it. We'll need to create the following files: server.js This is where we'll write some code to establish a connection with PostgreSQL using the pg package.
🌐
Medium
medium.com › @mavericks-db › how-to-connect-postgresql-with-node-js-bd2cbe87aa9e
How to Connect PostgreSQL with Node.JS | by Mavericks Balitaan | Medium
February 15, 2023 - Create a database.js file in the root directory. const { Client } = require("pg"); const client = new Client({ host: "localhost", user: "postgres", port: 5432, password: "your_password", database: "your_database_name", }); client.connect(); ...
🌐
Medium
medium.com › @dannibla › connecting-nodejs-postgresql-f8967b9f5932
How to Connect PostgreSQL with NodeJs Application? | by Daniel J Abraham | Medium
December 8, 2021 - After addingpackage.json and app.js files Create a table & insert some default value in PostgreSQL
🌐
Medium
medium.com › swlh › connect-postgresql-with-node-js-4ded3e81e31a
Connect PostgreSQL with Node.js. Here we are using the most popular… | by Amol Gunjal | The Startup | Medium
July 9, 2020 - ... const client = new Client() client.query(‘SELECT NOW()’, (err, res) => { console.log(err, res) client.end() }) The default values for the environment variables used are: PGHOST=’localhost’ PGUSER=process.env.USER PGDATABASE=proc...