Connect to PostgreSQL
Hyperdrive supports PostgreSQL and PostgreSQL-compatible databases, popular drivers and Object Relational Mapper (ORM) libraries that use those drivers.
To create a Hyperdrive that connects to an existing PostgreSQL database, use the wrangler CLI or the Cloudflare dashboard ↗.
When using wrangler, replace the placeholder value provided to --connection-string
with the connection string for your database:
# wrangler v3.11 and above requirednpx wrangler hyperdrive create my-first-hyperdrive --connection-string="postgres://user:password@database.host.example.com:5432/databasenamehere"
The command above will output the ID of your Hyperdrive, which you will need to set in the Wrangler configuration file for your Workers project:
{ "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>"
This will allow Hyperdrive to generate a dynamic connection string within your Worker that you can pass to your existing database driver. Refer to Driver examples to learn how to set up a database driver with Hyperdrive.
Refer to the Examples documentation for step-by-step guides on how to set up Hyperdrive with several popular database providers.
Hyperdrive uses Workers TCP socket support to support TCP connections to databases. The following table lists the supported database drivers and the minimum version that works with Hyperdrive:
Driver | Documentation | Minimum Version Required | Notes |
---|---|---|---|
Postgres.js | Postgres.js documentation ↗ | postgres@3.4.4 | Supported in both Workers & Pages. |
node-postgres - pg | node-postgres - pg documentation ↗ | pg@8.13.0 | 8.11.4 introduced a bug with URL parsing and will not work. 8.11.5 fixes this. Requires compatibility_flags = ["nodejs_compat"] and compatibility_date = "2024-09-23" - refer to Node.js compatibility. Requires wrangler 3.78.7 or later. |
Drizzle | Drizzle documentation ↗ | 0.26.2 ^ | |
Kysely | Kysely documentation ↗ | 0.26.3 ^ | |
rust-postgres ↗ | rust-postgres documentation ↗ | v0.19.8 | Use the query_typed ↗ method for best performance. |
^ The marked libraries use node-postgres
as a dependency.
Other drivers and ORMs not listed may also be supported: this list is not exhaustive.
Node.js compatibility is required for database drivers, including Postgres.js, and needs to be configured for your Workers project.
To enable both built-in runtime APIs and polyfills for your Worker or Pages project, add the nodejs_compat
compatibility flag to your Wrangler configuration file, and set your compatibility date to September 23rd, 2024 or later. This will enable Node.js compatibility for your Workers project.
{ "compatibility_flags": [ "nodejs_compat" ], "compatibility_date": "2024-09-23"}
compatibility_flags = [ "nodejs_compat" ]compatibility_date = "2024-09-23"
The following examples show you how to:
- Create a database client with a database driver.
- Pass the Hyperdrive connection string and connect to the database.
- Query your database via Hyperdrive.
The following Workers code shows you how to use Postgres.js ↗ with Hyperdrive.
Install Postgres.js ↗:
npm i postgres@>3.4.5
yarn add postgres@>3.4.5
pnpm add postgres@>3.4.5
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 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>;
Install the node-postgres
driver:
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(); } },};
To identify active connections to your Postgres database server from Hyperdrive:
- Hyperdrive's connections to your database will show up with
Cloudflare Hyperdrive
as theapplication_name
in thepg_stat_activity
table. - Run
SELECT DISTINCT usename, application_name FROM pg_stat_activity WHERE application_name = 'Cloudflare Hyperdrive'
to show whether Hyperdrive is currently holding a connection (or connections) open to your database.
- Refer to the list of supported database integrations to understand other ways to connect to existing databases.
- Learn more about how to use the Socket API in a Worker.
- Understand the protocols supported by Workers.
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