{"id":2284,"date":"2026-07-20T12:43:14","date_gmt":"2026-07-20T10:43:14","guid":{"rendered":"https:\/\/kindsonthegenius.com\/blog\/how-to-connect-node-js-to-postgresql-database-and-fetch-data-step-by-step\/"},"modified":"2026-08-26T21:14:41","modified_gmt":"2026-08-26T19:14:41","slug":"how-to-connect-node-js-to-postgresql-database-and-fetch-data-step-by-step","status":"publish","type":"post","link":"https:\/\/kindsonthegenius.com\/blog\/how-to-connect-node-js-to-postgresql-database-and-fetch-data-step-by-step\/","title":{"rendered":"How to Connect Node.js to PostgreSQL Database and Fetch Data \u2013 Step by Step"},"content":{"rendered":"<p><!-- ktg-updated-banner --><\/p>\n<p><em>Updated August 2026 \u2014 full tutorial restored for this URL.<\/em><\/p>\n<p>This tutorial connects <strong>Node.js<\/strong> to <strong>PostgreSQL<\/strong> using the official <code>pg<\/code> driver, with a pool and a small Express endpoint that fetches rows.<\/p>\n<ol>\n<li><a href=\"#t1\">Install PostgreSQL and create a database<\/a><\/li>\n<li><a href=\"#t2\">Install pg and dotenv<\/a><\/li>\n<li><a href=\"#t3\">Create a connection pool<\/a><\/li>\n<li><a href=\"#t4\">Fetch data in a route<\/a><\/li>\n<li><a href=\"#t5\">Error handling and next steps<\/a><\/li>\n<\/ol>\n<p><strong id=\"t1\">1. Install PostgreSQL and create a database<\/strong><\/p>\n<pre><code>CREATE DATABASE tutorial;\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  name TEXT NOT NULL,\n  email TEXT UNIQUE NOT NULL\n);\nINSERT INTO users(name, email) VALUES ('Kindson', 'kindson@example.com');\n<\/code><\/pre>\n<p><strong id=\"t2\">2. Install pg and dotenv<\/strong><\/p>\n<pre><code>npm init -y\nnpm install express pg dotenv\n<\/code><\/pre>\n<pre><code># .env\nDATABASE_URL=postgres:\/\/postgres:password@localhost:5432\/tutorial\nPORT=3000\n<\/code><\/pre>\n<p><strong id=\"t3\">3. Create a connection pool<\/strong><\/p>\n<pre><code>\/\/ db.js\nrequire('dotenv').config();\nconst { Pool } = require('pg');\nconst pool = new Pool({ connectionString: process.env.DATABASE_URL });\nmodule.exports = { pool };\n<\/code><\/pre>\n<p><strong id=\"t4\">4. Fetch data in a route<\/strong><\/p>\n<pre><code>\/\/ server.js\nconst express = require('express');\nconst { pool } = require('.\/db');\nconst app = express();\n\napp.get('\/users', async (req, res) => {\n  try {\n    const result = await pool.query(\n      'SELECT id, name, email FROM users ORDER BY id ASC'\n    );\n    res.json(result.rows);\n  } catch (err) {\n    console.error(err);\n    res.status(500).json({ error: 'Database error' });\n  }\n});\n\napp.listen(process.env.PORT, () => console.log('listening'));\n<\/code><\/pre>\n<p><strong id=\"t5\">5. Error handling and next steps<\/strong><\/p>\n<ul>\n<li>Always use parameterized queries (<code>$1<\/code>) for user input.<\/li>\n<li>Call <code>pool.end()<\/code> on graceful shutdown in long-running workers.<\/li>\n<li>For Docker, point <code>DATABASE_URL<\/code> host to the Compose service name <code>postgres<\/code>.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Updated August 2026 \u2014 full tutorial restored for this URL. This tutorial connects Node.js to PostgreSQL using the official pg driver, with a pool and &hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"pagelayer_contact_templates":[],"_pagelayer_content":"","footnotes":""},"categories":[35],"tags":[],"class_list":["post-2284","post","type-post","status-publish","format-standard","hentry","category-algorithms"],"acf":[],"_links":{"self":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/2284","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/comments?post=2284"}],"version-history":[{"count":2,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/2284\/revisions"}],"predecessor-version":[{"id":2452,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/2284\/revisions\/2452"}],"wp:attachment":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/media?parent=2284"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/categories?post=2284"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/tags?post=2284"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}