Skip to content
Cloudflare Docs

node-postgres (pg)

node-postgres (pg) is a widely-used PostgreSQL driver for Node.js applications. This example demonstrates how to use node-postgres with Cloudflare Hyperdrive in a Workers application.

Install the node-postgres driver:

Terminal window
npm i pg@>8.13.0

If using TypeScript, install the types package:

Terminal window
npm i -D @types/pg

Add the required Node.js compatibility flags and Hyperdrive binding to your wrangler.jsonc file:

{
"compatibility_flags": [
"nodejs_compat"
],
"compatibility_date": "2024-09-23",
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<your-hyperdrive-id-here>"
}
]
}

Create a new Client instance and pass the Hyperdrive connectionString:

// filepath: src/index.ts
import { Client } from "pg";
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
// Create a new client instance for each request.
const client = new Client({
connectionString: env.HYPERDRIVE.connectionString,
});
try {
// Connect to the database
await client.connect();
console.log("Connected to PostgreSQL database");
// Perform a simple query
const result = await client.query("SELECT * FROM pg_tables");
// Clean up the client after the response is returned, before the Worker is killed
env.waitUntil(client.end());
return Response.json({
success: true,
result: result.rows,
});
} catch (error: any) {
console.error("Database error:", error.message);
return Response.error();
}
},
};