Postgres.js
Postgres.js ↗ is a modern, fully-featured PostgreSQL driver for Node.js. This example demonstrates how to use Postgres.js with Cloudflare Hyperdrive in a Workers application.
Install Postgres.js ↗:
npm i postgres@>3.4.5yarn add postgres@>3.4.5pnpm add postgres@>3.4.5Add 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 Worker that connects to your PostgreSQL database via Hyperdrive:
// filepath: src/index.tsimport postgres from "postgres";
export default {  async fetch(    request: Request,    env: Env,    ctx: ExecutionContext,  ): Promise<Response> {    // Create a database client that connects to your database via Hyperdrive    // using the Hyperdrive credentials    const sql = postgres(env.HYPERDRIVE.connectionString, {      // Limit the connections for the Worker request to 5 due to Workers' limits on concurrent external connections      max: 5,      // If you are not using array types in your Postgres schema, disable `fetch_types` to avoid an additional round-trip (unnecessary latency)      fetch_types: false,    });
    try {      // A very simple test query      const result = await sql`select * from pg_tables`;
      // Clean up the client, ensuring we don't kill the worker before that is      // completed.      ctx.waitUntil(sql.end());
      // Return result rows as JSON      return Response.json({ success: true, result: result });    } catch (e: any) {      console.error("Database error:", e.message);
      return Response.error();    }  },} satisfies ExportedHandler<Env>;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