September 18, 2026

How to Connect Node.js to PostgreSQL Database and Fetch Data – Step by Step

Updated August 2026 — full tutorial restored for this URL.

This tutorial connects Node.js to PostgreSQL using the official pg driver, with a pool and a small Express endpoint that fetches rows.

  1. Install PostgreSQL and create a database
  2. Install pg and dotenv
  3. Create a connection pool
  4. Fetch data in a route
  5. Error handling and next steps

1. Install PostgreSQL and create a database

CREATE DATABASE tutorial;
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT UNIQUE NOT NULL
);
INSERT INTO users(name, email) VALUES ('Kindson', 'kindson@example.com');

2. Install pg and dotenv

npm init -y
npm install express pg dotenv
# .env
DATABASE_URL=postgres://postgres:password@localhost:5432/tutorial
PORT=3000

3. Create a connection pool

// db.js
require('dotenv').config();
const { Pool } = require('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
module.exports = { pool };

4. Fetch data in a route

// server.js
const express = require('express');
const { pool } = require('./db');
const app = express();

app.get('/users', async (req, res) => {
  try {
    const result = await pool.query(
      'SELECT id, name, email FROM users ORDER BY id ASC'
    );
    res.json(result.rows);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Database error' });
  }
});

app.listen(process.env.PORT, () => console.log('listening'));

5. Error handling and next steps

  • Always use parameterized queries ($1) for user input.
  • Call pool.end() on graceful shutdown in long-running workers.
  • For Docker, point DATABASE_URL host to the Compose service name postgres.

Kindson Munonye

Kindson Munonye is a software engineer and technical author covering machine learning, statistics, REST APIs, Python, and software engineering. He publishes free tutorials on The Genius Blog and live classes on Alkademy. GitHub · LinkedIn · About · Alkademy

View all posts by Kindson Munonye →
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted