node-postgres (pg)
Last reviewed: 9 months ago
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:
npm i pg@>8.16.3yarn add pg@>8.16.3pnpm add pg@>8.16.3If using TypeScript, install the types package:
npm i -D @types/pgyarn add -D @types/pgpnpm add -D @types/pgAdd the required Node.js compatibility flags and Hyperdrive binding to your wrangler.jsonc file:
{ // required for database drivers to function "compatibility_flags": [ "nodejs_compat" ], // Set this to today's date "compatibility_date": "2026-02-19", "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "<your-hyperdrive-id-here>" } ]}compatibility_flags = [ "nodejs_compat" ]# Set this to today's datecompatibility_date = "2026-02-19"
[[hyperdrive]]binding = "HYPERDRIVE"id = "<your-hyperdrive-id-here>"Create a new Client instance and pass the Hyperdrive connectionString:
// filepath: src/index.tsimport { Client } from "pg";
export default { async fetch( request: Request, env: Env, ctx: ExecutionContext, ): Promise<Response> { // Create a new client instance for each request. Hyperdrive maintains the // underlying database connection pool, so creating a new client is fast. const client = new Client({ connectionString: env.HYPERDRIVE.connectionString, });
try { // Connect to the database await client.connect();
// Perform a simple query const result = await client.query("SELECT * FROM pg_tables");
return Response.json({ success: true, result: result.rows, }); } catch (error: any) { console.error("Database error:", error.message);
return new Response("Internal error occurred", { status: 500 }); } },};