Step-by-step guide for setting up PostgreSQL with Node.js using the pg package

Priyanshu
2 min readAug 2, 2024

What is PostgreSQL?

PostgreSQL is a powerful, open-source relational database system. Known for its robustness, performance, and advanced features, PostgreSQL’s JSON support allows it to handle document-based workloads, making it competitive with NoSQL databases while still providing relational capabilities. Additionally, it provides ACID compliance and concurrency.

Setup Guide

Step 1: Create an Account on NeonDB

First, create an account on NeonDB. Once registered, create a new project. You will then be redirected to the console where you can manage your database.

Step 2: Obtain the Connection String

In the NeonDB console, you’ll see a connection string that looks something like this:

postgresql://owner:<password>@ep-rapid-snowflake-d12345t.us-east-2.aws.neon.tech/postres?sslmode=require

Step 3: Initialize a New Node.js Project

Run the following command in your terminal to initialize a new Node.js project:

npm init -y

Step 4: Create an index.js File

In the root of your project folder, create a file named index.js.

Step 5: Install Required Packages

Install Express and the PostgreSQL client for Node.js using npm:

npm install express pg

Step 6: Set Up Environment Variables

To store sensitive data securely, create a .env file in your project directory and add your database credentials:

HOST=ep-rapid-snowflake-d12345t.us-east-2.aws.neon.tech
USER=owner
PASSWORD=<your_password>
DATABASE=postres

Step 7: Write the Code

Here is the code for setting up an Express server and connecting to your PostgreSQL database using the pg package:

require('dotenv').config();
const express = require('express');
const { Client } = require('pg');

const app = express();
app.use(express.json());

const client = new Client({
host: process.env.HOST,
port: 5432,
database: process.env.DATABASE,
user: process.env.USER,
password: process.env.PASSWORD,
ssl: {
rejectUnauthorized: false,
},
});

async function connectDb() {
try {
await client.connect();
console.log("Connected to the database");
} catch (e) {
console.error("Error connecting to the database:", e);
throw new Error("Error connecting to the database");
}
}

connectDb();

app.listen(8000, () => {
console.log("Server is running on port 8000");
});

Step 8: Run Your Application

Run the following command to start your server:

node index.js

You will see the following text on the CLI

Server is running on port 8000
Connected to the database

BOOM You’ve successfully set up a Node.js application with PostgreSQL using the pg package

--

--

Priyanshu
Priyanshu

Written by Priyanshu

Software Engineer l NestJs | ReactJs | ExpressJs | NodeJs

No responses yet