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:
npm i pg@>8.13.0
yarn add pg@>8.13.0
pnpm add pg@>8.13.0
If using TypeScript, install the types package:
npm i -D @types/pg
yarn add -D @types/pg
pnpm add -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>" } ]}
# required for database drivers to functioncompatibility_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.tsimport { 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(); } },};
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Products
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark