Connect with Node.js
Learn how to connect to PhoenixDB from your Node.js application.
Install Dependencies
Install the pg package:
npm install pgFor TypeScript, also install types: npm install -D @types/pg
Environment Setup
Add your connection string to .env:
DATABASE_URL="postgresql://postgres:YOUR_PASSWORD@abc123.server1.phoenixdb.space:5432/mydb?sslmode=require"
Basic Connection
Create a connection using the Pool class:
db.js
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false }
});
// Query helper
async function query(text, params) {
const client = await pool.connect();
try {
const result = await client.query(text, params);
return result;
} finally {
client.release();
}
}
module.exports = { pool, query };Usage Example
app.js
const { query } = require('./db');
async function main() {
// Create table
await query(`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Insert data
const result = await query(
'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *',
['John Doe', 'john@example.com']
);
console.log('Created user:', result.rows[0]);
// Query data
const users = await query('SELECT * FROM users');
console.log('All users:', users.rows);
}
main().catch(console.error);TypeScript Example
db.ts
import { Pool, QueryResult } from 'pg';
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false }
});
export async function query<T = any>(
text: string,
params?: any[]
): Promise<QueryResult<T>> {
const client = await pool.connect();
try {
return await client.query<T>(text, params);
} finally {
client.release();
}
}
export default pool;Connection Pool Best Practices
Use a Single Pool
Create one Pool instance and reuse it throughout your application. Don't create a new pool for each query.
Configure Pool Size
Adjust pool size based on your workload:
const pool = new Pool({ max: 20, min: 5, ... });Always Release Clients
Use try/finally to ensure clients are released back to the pool, even if an error occurs.