How to connect Node.js to PostgreSQL
Connecting Node.js to PostgreSQL provides robust relational database capabilities for applications requiring ACID compliance and complex queries.
As the creator of CoreUI with extensive Node.js development experience since 2014, I’ve integrated PostgreSQL with Node.js in numerous enterprise applications for financial data and user management systems.
The most reliable approach uses the pg library with connection pooling for optimal performance and connection management.
This method ensures secure, efficient database access while handling connection failures and maintaining data consistency.
Use the pg library with connection pooling to establish secure and efficient PostgreSQL connections.
const { Pool } = require('pg')
class PostgreSQLConnection {
constructor() {
this.pool = new Pool({
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || 5432,
database: process.env.DB_NAME || 'myapp',
user: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
})
this.pool.on('error', (err) => {
console.error('Unexpected error on idle client', err)
})
}
async query(text, params) {
try {
const result = await this.pool.query(text, params)
return result
} catch (error) {
console.error('Database query error:', error)
throw error
}
}
async getClient() {
return await this.pool.connect()
}
async close() {
await this.pool.end()
console.log('PostgreSQL pool closed')
}
}
// Usage
const db = new PostgreSQLConnection()
async function initializeApp() {
try {
// Test connection
const result = await db.query('SELECT NOW() as current_time')
console.log('Database connected:', result.rows[0].current_time)
// Example query
const users = await db.query(
'SELECT * FROM users WHERE email = $1',
['[email protected]']
)
console.log('Users found:', users.rows)
} catch (error) {
console.error('Database initialization error:', error)
}
}
initializeApp()
// Graceful shutdown
process.on('SIGTERM', async () => {
await db.close()
process.exit(0)
})
This code creates a PostgreSQL connection pool using the pg library with proper configuration for production use. The connection class provides query methods with error handling and supports both simple queries and parameterized queries for SQL injection prevention. The pool automatically manages connections and handles reconnection scenarios.
Best Practice Note:
This is the PostgreSQL connection architecture we use in CoreUI enterprise backend services for reliable data management. Always use parameterized queries to prevent SQL injection and implement proper connection pooling for optimal performance in production environments.



