Connect to a private database
This example demonstrates how to query a private PostgreSQL database from a Worker using Workers VPC and Hyperdrive. The Worker connects to a database that is not exposed to the public Internet, with Hyperdrive providing connection pooling and query acceleration.
- A PostgreSQL database running in your private network (for example, on port 5432)
- A Cloudflare Tunnel connected to the private network where your database runs
- A Cloudflare account with Workers VPC access
If you do not already have a tunnel running in the same network as your database, create one.
-
Go to the Workers VPC dashboard ↗ and select the Tunnels tab.
-
Select Create to create a tunnel.
-
Enter a name for your tunnel and select Save tunnel.
-
Choose your operating system and architecture. The dashboard will provide installation instructions.
-
Follow the provided commands to download, install, and run
cloudflaredwith your unique token.
The tunnel must be able to reach your database host and port from within the private network. For full tunnel documentation, refer to Cloudflare Tunnel for Workers VPC.
Create a VPC Service of type tcp that points to your database:
npx wrangler vpc service create my-postgres-db \ --type tcp \ --tcp-port 5432 \ --app-protocol postgresql \ --tunnel-id <YOUR_TUNNEL_ID> \ --ipv4 <YOUR_DATABASE_IP>Replace <YOUR_TUNNEL_ID> with the tunnel ID from step 1 and <YOUR_DATABASE_IP> with the private IP address of your database (for example, 10.0.0.5).
The command returns a service ID. Save this value for the next step.
Use the --service-id flag to point Hyperdrive at the VPC Service you created:
npx wrangler hyperdrive create my-vpc-database \ --service-id <YOUR_VPC_SERVICE_ID> \ --database <DATABASE_NAME> \ --user <DATABASE_USER> \ --password <DATABASE_PASSWORD> \ --scheme postgresqlReplace <YOUR_VPC_SERVICE_ID> with the service ID from step 2, and provide your database name, user, and password.
The command outputs a Hyperdrive configuration ID. Copy this for the next step.
You must create a binding in your Wrangler configuration file for your Worker to connect to your Hyperdrive configuration. Bindings allow your Workers to access resources, like Hyperdrive, on the Cloudflare developer platform.
To bind your Hyperdrive configuration to your Worker, add the following to the end of your Wrangler file:
{ "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "<YOUR_DATABASE_ID>" // the ID associated with the Hyperdrive you just created } ]}[[hyperdrive]]binding = "HYPERDRIVE"id = "<YOUR_DATABASE_ID>"Specifically:
- The value (string) you set for the
binding(binding name) will be used to reference this database in your Worker. In this tutorial, name your bindingHYPERDRIVE. - The binding must be a valid JavaScript variable name ↗. For example,
binding = "hyperdrive"orbinding = "productionDB"would both be valid names for the binding. - Your binding is available in your Worker at
env.<BINDING_NAME>.
If you wish to use a local database during development, you can add a localConnectionString to your Hyperdrive configuration with the connection string of your database:
{ "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "<YOUR_DATABASE_ID>", // the ID associated with the Hyperdrive you just created "localConnectionString": "<LOCAL_DATABASE_CONNECTION_URI>" } ]}[[hyperdrive]]binding = "HYPERDRIVE"id = "<YOUR_DATABASE_ID>"localConnectionString = "<LOCAL_DATABASE_CONNECTION_URI>"Install the node-postgres driver:
npm i pg@>8.16.3 yarn add pg@>8.16.3 pnpm add pg@>8.16.3 bun add pg@>8.16.3 If using TypeScript, install the types package:
npm i -D @types/pg yarn add -D @types/pg pnpm add -D @types/pg bun add -d @types/pg Add 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-05-05", "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "<your-hyperdrive-id-here>" } ]}compatibility_flags = [ "nodejs_compat" ]# Set this to today's datecompatibility_date = "2026-05-05"
[[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 }); } },};Deploy your Worker:
npx wrangler deploySend a request to verify the connection:
curl https://<YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.devA successful response returns a JSON array of rows from your database.
- Learn more about how Hyperdrive works
- Configure query caching for Hyperdrive
- Review VPC Service configuration options including TLS certificate verification
- Explore other examples