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.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:
{  "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");
      return Response.json({        success: true,        result: result.rows,      });    } catch (error: any) {      console.error("Database error:", error.message);
      new Response("Internal error occurred", { status: 500 });    }  },};Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- 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