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.
- Install PostgreSQL and create a database
- Install pg and dotenv
- Create a connection pool
- Fetch data in a route
- 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_URLhost to the Compose service namepostgres.