Learn how to integrate PostgreSQL with Node.js, from setup and connection to CRUD operations, using popular libraries like ‘pg’.
Table of content
PostgreSQL is a powerful, open source relational database. Combining it with Node.js allows web developers to build scalable, efficient applications with robust data storage. In this guide, we’ll walk you through connecting Node.js to PostgreSQL, performing CRUD operations, and ensuring best practices for security and performance.
psql -U postgres
CREATE DATABASE mydb;
CREATE USER devuser WITH ENCRYPTED PASSWORD 'devpass';
GRANT ALL PRIVILEGES ON DATABASE mydb TO devuser;
In your Node.js project folder, install the PostgreSQL client for Node.js:
npm install pg
Use the pg library to connect to your PostgreSQL database. Below is a simple configuration using a connection pool:
const { Pool } = require('pg');
const pool = new Pool({
user: 'devuser',
host: 'localhost',
database: 'mydb',
password: 'devpass',
port: 5432,
});
// Testing the connection
pool.query('SELECT NOW()', (err, res) => {
if (err) {
console.error('Connection error', err.stack);
} else {
console.log('Connected:', res.rows[0]);
}
pool.end();
});
// Inserting a row
pool.query('INSERT INTO users(name, email) VALUES($1, $2)', ['Alice', 'alice@example.com']);
// Fetching users
pool.query('SELECT * FROM users', (err, res) => {
console.log(res.rows);
});
// Updating user email
pool.query('UPDATE users SET email = $1 WHERE name = $2', ['alice@fulldev.pl', 'Alice']);
// Deleting a user
pool.query('DELETE FROM users WHERE name = $1', ['Alice']);
dotenv
to manage sensitive information.try/catch
with async/await.project/
|-- db.js // PostgreSQL connection setup
|-- index.js // App entry point
|-- models/ // DB query functions
Integrating PostgreSQL with Node.js is straightforward and enables the creation of efficient, scalable web applications. With tools like pg, you can effortlessly manage your data and build modern web services.