I’m a big fan of postgres.js ( https://github.com/porsager/postgres ). It’s minial and straightforward but you have to know how to sql. In fact I don’t really like ORMs. Most of the time I feel it makes things over complicated for nothing and I’ll never use any other databases than postgres. Dev mode included. As everyone should in my opinion (trying to get each environements the same for testing/debuging purpose is a hughe plus). Moreover it’s fast. Answer from Deleted User on reddit.com
🌐
node-postgres
node-postgres.com
node-postgres
node-postgres is a collection of node.js modules for interfacing with your PostgreSQL database. It has support for callbacks, promises, async/await, connection pooling, prepared statements, cursors, streaming results, C/C++ bindings, rich type parsing, and more!
🌐
npm
npmjs.com › package › pg
pg - npm
June 19, 2026 - Non-blocking PostgreSQL client for Node.js.
      » npm install pg
    
Published   Jun 19, 2026
Version   8.22.0
Discussions

Which postgreSQL node.js client library to choose today?
I’m a big fan of postgres.js ( https://github.com/porsager/postgres ). It’s minial and straightforward but you have to know how to sql. In fact I don’t really like ORMs. Most of the time I feel it makes things over complicated for nothing and I’ll never use any other databases than postgres. Dev mode included. As everyone should in my opinion (trying to get each environements the same for testing/debuging purpose is a hughe plus). Moreover it’s fast. More on reddit.com
🌐 r/node
47
27
August 17, 2023
postgresql - How to make connection to Postgres via Node.js - Stack Overflow
I find myself trying to create a postgres database, so I installed postgres and started a server with initdb /usr/local/pgsql/data, then I started that instance with postgres -D /usr/local/pgsql/da... More on stackoverflow.com
🌐 stackoverflow.com
What is the proper way to use the node.js postgresql module?
I am writing a node.js app on Heroku and using the pg module. I can't figure out the "right" way to get a client object for each request that I need to query the database. The documentation uses c... More on stackoverflow.com
🌐 stackoverflow.com
PostgresJs: PostgreSQL client for Node.js and Deno
No “fancy” and bleeding abstractions like something like Prisma, not convoluted type annotations like other TS libs, no, just plain SQL statements in the best JavaScript way of doing it · I discovered learning to do Postgres a couple years ago, after getting sick of trying to hack Prisma, ... More on news.ycombinator.com
🌐 news.ycombinator.com
143
308
October 23, 2023
🌐
GitHub
github.com › porsager › postgres
GitHub - porsager/postgres: Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare · GitHub
Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare - porsager/postgres
Starred by 8.7K users
Forked by 355 users
Languages   JavaScript
🌐
GitHub
github.com › brianc › node-postgres
GitHub - brianc/node-postgres: PostgreSQL client for node.js. · GitHub
Non-blocking PostgreSQL client for Node.js (and bun, deno, cloudflare, etc...).
Starred by 13.2K users
Forked by 1.3K users
Languages   JavaScript 79.4% | TypeScript 19.6%
🌐
Reddit
reddit.com › r/node › which postgresql node.js client library to choose today?
r/node on Reddit: Which postgreSQL node.js client library to choose today?
August 17, 2023 -

Raw queries, ORM, Query builder, code generators etc which pg client library would you choose with Node.js today in production?

Popular ones are: 1] Knex 2] Sequalize 3] TypeORM 4] Prisma 5] Drizzle 6] MikroORM

If you can also comment on "why" that would also be great. If there is any new recommendation that is also great

🌐
Holt
sql.holt.courses › lessons › data › nodejs-and-postgresql
Node.js and PostgreSQL – Complete Intro to SQL
We are going to be using the pg package which is the most common PostgreSQL client for Node.js. There are others but this is the one with the most direct access to the underlying queries which is what we want.
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.

Find elsewhere
🌐
node-postgres
node-postgres.com › features › connecting
Connection URI
1 week ago - import pg from 'pg' const { Pool, Client } = pg const connectionString = 'postgresql://dbuser:[email protected]:3211/mydb' const pool = new Pool({ connectionString, }) await pool.query('SELECT NOW()') await pool.end() const client = new Client({ connectionString, }) await client.connect() await client.query('SELECT NOW()') await client.end()
🌐
EnterpriseDB
enterprisedb.com › postgres-tutorials › how-quickly-build-api-using-nodejs-postgresql
How to quickly build an API using Node.js & PostgreSQL | EDB
This article describes how you can use Node.js and PostgreSQL to create an API and provides an example for how to create a table.
🌐
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.
🌐
Medium
medium.com › @mateogalic112 › how-to-build-a-node-js-api-with-postgresql-and-typescript-best-practices-and-tips-84fee3d1c46c
How to Build a Node.js API with PostgreSQL and TypeScript: Best Practices and Tips | by Mateo Galic | Medium
November 17, 2024 - For every Node.js project I run locally, the first thing I do is start the PostgreSQL database from a Docker container. This process is super easy and definitely not something to be afraid of. With Docker, you don’t need to have PostgreSQL installed on your machine.
🌐
OVHcloud
us.ovhcloud.com › home › how to access a postgresql from node.js application ?
How to access a PostgreSQL from Node.js application ?
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?
Top answer
1 of 6
166

I'm the author of node-postgres. First, I apologize the documentation has failed to make the right option clear: that's my fault. I'll try to improve it. I wrote a Gist just now to explain this because the conversation grew too long for Twitter.

Using pg.connect is the way to go in a web environment.

PostgreSQL server can only handle 1 query at a time per connection. That means if you have 1 global new pg.Client() connected to your backend your entire app is bottleknecked based on how fast postgres can respond to queries. It literally will line everything up, queuing each query. Yeah, it's async and so that's alright...but wouldn't you rather multiply your throughput by 10x? Use pg.connect set the pg.defaults.poolSize to something sane (we do 25-100, not sure the right number yet).

new pg.Client is for when you know what you're doing. When you need a single long lived client for some reason or need to very carefully control the life-cycle. A good example of this is when using LISTEN/NOTIFY. The listening client needs to be around and connected and not shared so it can properly handle NOTIFY messages. Other example would be when opening up a 1-off client to kill some hung stuff or in command line scripts.

One very helpful thing is to centralize all access to your database in your app to one file. Don't litter pg.connect calls or new clients throughout. Have a file like db.js that looks something like this:

module.exports = {
   query: function(text, values, cb) {
      pg.connect(function(err, client, done) {
        client.query(text, values, function(err, result) {
          done();
          cb(err, result);
        })
      });
   }
}

This way you can change out your implementation from pg.connect to a custom pool of clients or whatever and only have to change things in one place.

Have a look at the node-pg-query module that does just this.

2 of 6
26

I am the author of pg-promise, which simplifies the use of node-postgres via promises.

It addresses the issues about the right way of connecting to and disconnecting from the database, using the connection pool implemented by node-postgres, among other things, like automated transactions.

An individual request in pg-promise boils down to just what's relevant to your business logic:

db.any('SELECT * FROM users WHERE status = $1', ['active'])
    .then(data => {
        console.log('DATA:', data);
    })
    .catch(error => {
        console.log('ERROR:', error);
    });

i.e. you do not need to deal with connection logic when executing queries, because you set up the connection only once, globally, like this:

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

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

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

You can find many more examples in Learn by Example tutorial, or on the project's home page.

🌐
npm
npmjs.com › package › postgres
postgres - npm
April 5, 2026 - Fastest full featured PostgreSQL client for Node.js. Latest version: 3.4.9, last published: 4 months ago. Start using postgres in your project by running `npm i postgres`. There are 1158 other projects in the npm registry using postgres.
      » npm install postgres
    
Published   Apr 05, 2026
Version   3.4.9
🌐
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 - In this tutorial, you’ll use node-postgres to connect and query the PostgreSQL (Postgres in short) database. First, you’ll create a database user and the database in Postgres. You will then connect your application to the Postgres database using the node-postgres module.
🌐
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 - Working with APIs to facilitate communication between software systems is crucial for modern web developers. In this tutorial, we’ll create a CRUD RESTful API in a Node.js environment that runs on an Express server and uses a PostgreSQL database.
🌐
Stack Abuse
stackabuse.com › using-postgresql-with-nodejs-and-node-postgres
Using PostgreSQL with Node.js and node-postgres
March 6, 2020 - PostgreSQL is a really popular, free, open-source relational database. The node-postgres module is a widely-employed module that bridges Node with it. In this article, we'll be developing simple CRUD functionality for a PostgreSQL database.
🌐
npm
npmjs.com › package › postgresql-client
postgresql-client - npm
July 22, 2024 - import {Connection} from 'postgresql-client'; // Create connection const connection = new Connection('postgres://localhost'); // Connect to database server await connection.connect(); // Execute query and fetch rows const result = await connection.query( 'select * from cities where name like $1', {params: ['%york%']}); const rows: any[] = result.rows; // Do what ever you want with rows // Disconnect from server await connection.close();
      » npm install postgresql-client
    
Published   Jul 22, 2024
Version   2.13.0
🌐
Hacker News
news.ycombinator.com › item
PostgresJs: PostgreSQL client for Node.js and Deno | Hacker News
October 23, 2023 - No “fancy” and bleeding abstractions like something like Prisma, not convoluted type annotations like other TS libs, no, just plain SQL statements in the best JavaScript way of doing it · I discovered learning to do Postgres a couple years ago, after getting sick of trying to hack Prisma, ...
🌐
This Dot Labs
thisdot.co › blog › connecting-to-postgresql-with-node-js
Connecting to PostgreSQL with Node.js - This Dot Labs
February 14, 2023 - node-postgres is a pure JavaScript library that allows you to interact with a PostgreSQL database. It supports modern features such as aync / await and is well maintained.