How to connect to a PostgreSQL database in Node.js

Connect to Postgres database in Node js using pg and parse-database-url packages

Jul 28, 2020
featured image
A simple example about how to connect to a PostgreSQL database using Node.js

Let’s create a folder to host our example. Open a terminal and type:

mkdir node-js-postgresql
Enter to the folder
cd node-js-postgresql
Use package.json generator. Follow the steps
npm init
npm install
Install pg module in our project
npm install pg --save
In case you have a database url connection you will have to parse it. There’s a module to parse such as url. Example url:
Install the module
npm install parse-database-url --save
Create a file called db_helper.js
const parseDbUrl = require("parse-database-url");
//we have our connection url in an environment config variable. Each developer will have his own
//a connection url will look like this:
const dbConfig = parseDbUrl(process.env.DATABASE_URL);
const Pool = require("pg").Pool;
const pool = new Pool({
    user: dbConfig.user,
    database: dbConfig.database,
    password: dbConfig.password,
    port: dbConfig.port,
    ssl: true,
module.exports.execute = pool;
In the line number 6 we have a call to a configuration environment variable
It’s a good way to avoid versioning sensitive data like a database connection or other credentials. To run this example you can just hard-code it Create a file called index.js
const dbHelper = require("./db_helper");
//deal with the promise
    .then(user => {;
    .catch(error => {
 * @param userId
 * @returns a Promise with the user row for the given id
 * @throws error if there's a connection issue or if the user was not found by the id
async function findUserById(userId) {
    const query = "SELECT * FROM users WHERE id = $1 LIMIT 1";
    const bindings = [userId];
    const result = await dbHelper.execute.query(query, bindings);
    if (result.rows.length > 0) {
        return result.rows[0];
    } else {
        throw Error("User not found by id " + userId);

Run the example
node index.js
That’s it 🙂 Full source code: Photo by Kevin Ku on Unsplash
postgres pg sql nodejs dev