Last modified: Jul 21, 2025 By Alexander Williams
Install PostgreSQL (pg) in Node.js - Quick Guide
The pg module is a popular PostgreSQL client for Node.js. It helps you connect and interact with PostgreSQL databases. This guide will show you how to install and use it.
Table Of Contents
Prerequisites
Before installing the pg module, ensure you have:
- Node.js installed on your system. Check with node -v
.
- A PostgreSQL database running locally or remotely.
- Basic knowledge of JavaScript and Node.js.
node -v
v18.12.1
Install pg Module
Use npm to install the pg module. Run this command in your project folder:
npm install pg
This will add the module to your package.json
file. For TypeScript projects, you may also need TypeScript.
Basic Usage
Here’s a simple example to connect to a PostgreSQL database:
const { Pool } = require('pg');
const pool = new Pool({
user: 'your_username',
host: 'localhost',
database: 'your_database',
password: 'your_password',
port: 5432,
});
pool.query('SELECT NOW()', (err, res) => {
if (err) {
console.error(err);
return;
}
console.log(res.rows[0]);
pool.end();
});
{ now: 2023-10-05T12:34:56.789Z }
The Pool
class manages multiple connections. Use pool.query
to run SQL commands.
Using Environment Variables
Store database credentials securely using environment variables. Install dotenv for this.
require('dotenv').config();
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
});
Error Handling
Always handle errors to avoid crashes. Use try-catch blocks or promises.
pool.query('SELECT * FROM users')
.then(res => console.log(res.rows))
.catch(err => console.error(err));
Conclusion
The pg module makes PostgreSQL easy to use in Node.js. Follow this guide to install and connect to your database. For more modules, check our guide on MySQL2.