Connect to a private database
Last updated Apr 30, 2026 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.
Prerequisites
- 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
1. Set up a Cloudflare Tunnel
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.
2. Create a TCP VPC Service
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.
Note
If your database uses a self-signed certificate, add --cert-verification-mode verify_ca to the command above. Refer to TLS certificate verification mode for all options.
3. Create a Hyperdrive configuration
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 postgresql
Replace <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.
4. Bind Hyperdrive to a Worker
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>"
Note
Learn more about setting up Hyperdrive for local development.
5. Query the database
Install the node-postgres driver:
npmyarnpnpmbun
npm i pg@>8.16.3
yarn add pg@>8.16.3
pnpm add pg@>8.16.3
bun add pg@>8.16.3
Note
The minimum version of node-postgres required for Hyperdrive is 8.16.3.
If using TypeScript, install the types package:
npmyarnpnpmbun
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-10-27",
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<your-hyperdrive-id-here>"
}
]
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-10-27"
[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"
Create a new Client instance and pass the Hyperdrive connectionString:
// filepath: src/index.ts
import { 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 });
}
},
};
6. Deploy and test
Deploy your Worker:
npx wrangler deploy
Send a request to verify the connection:
curl https://<YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev
A successful response returns a JSON array of rows from your database.
Next steps
- Learn more about how Hyperdrive works
- Configure query caching for Hyperdrive
- Review VPC Service configuration options including TLS certificate verification
- Explore other examples
Was this helpful?
YesNo
On this page
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/workers-vpc/examples/private-database/#page","headline":"Connect to a private database","description":"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.","url":"https://developers.cloudflare.com/workers-vpc/examples/private-database/","inLanguage":"en","image":"https://developers.cloudflare.com/workers-vpc/examples/private-database/og.png?v=51911d82efb15602","dateModified":"2026-04-30","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
description: Use Workers VPC to read objects from a private S3-compatible bucket behind Cloudflare Tunnel. title: Access a private S3 bucket image: https://developers.cloudflare.com/workers-vpc/examples/private-s3-bucket/og.png?v=9aad1aead63f1047
Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/workers-vpc/llms.txt
Use this file to discover all available pages before exploring further.
Docs