Connect to a private database using Tunn·续

This will create a Hyperdrive configuration using the usual database information (database name, database host, database user, and database password).

In addition, it will also set the Access Client ID and the Access Client Secret of the Service Token. When Hyperdrive makes requests to the tunnel, requests will be intercepted by Access and validated using the credentials of the Service Token.

Note

When creating the Hyperdrive configuration for the private database, you must enter the <code>access-client-id</code> and the <code>access-client-secret</code>, and omit the <code>port</code>. Hyperdrive will route database messages to the public hostname of the tunnel, and the tunnel will rely on its service configuration (as configured in <a href="#12-connect-your-database-using-a-public-hostname">1.2. Connect your database using a public hostname</a>) to route requests to the database within your private network.

</details>

3. Query your Hyperdrive configuration from a Worker (optional)

To test your Hyperdrive configuration to the database using Cloudflare Tunnel and Access, use the Hyperdrive configuration ID in your Worker and deploy it.

3.1. Create a Hyperdrive binding

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 binding HYPERDRIVE.
  • The binding must be a valid JavaScript variable name ↗︎. For example, binding = "hyperdrive" or binding = "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.

3.2. Query your database

Validate that you can connect to your database from Workers and make queries.

Use node-postgres ↗︎ (pg) to send a test query to validate that the connection has been successful.

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 });
        }
    },
};

Now, deploy your Worker:

npx wrangler deploy

If you successfully receive the list of pg_tables from your database when you access your deployed Worker, your Hyperdrive has now been configured to securely connect to a private database using Cloudflare Tunnel and Cloudflare Access.

Use mysql2 ↗︎ to send a test query to validate that the connection has been successful.

Install the mysql2 ↗︎ driver:

npmyarnpnpmbun

npm i mysql2@>3.13.0
yarn add mysql2@>3.13.0
pnpm add mysql2@>3.13.0
bun add mysql2@>3.13.0

Note

mysql2 v3.13.0 or later is required

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 connection instance and pass the Hyperdrive parameters:

// mysql2 v3.13.0 or later is required
import { createConnection } from "mysql2/promise";

export default {
    async fetch(request, env, ctx): Promise<Response> {
        // Create a new connection on each request. Hyperdrive maintains the underlying
        // database connection pool, so creating a new connection is fast.
        const connection = await createConnection({
            host: env.HYPERDRIVE.host,
            user: env.HYPERDRIVE.user,
            password: env.HYPERDRIVE.password,
            database: env.HYPERDRIVE.database,
            port: env.HYPERDRIVE.port,

// Required to enable mysql2 compatibility for Workers
            disableEval: true,
        });

try {
            // Sample query
            const [results, fields] = await connection.query("SHOW tables;");

// Return result rows as JSON
            return Response.json({ results, fields });
        } catch (e) {
            console.error(e);
            return Response.json(
                { error: e instanceof Error ? e.message : e },
                { status: 500 },
            );
        }
    },
} satisfies ExportedHandler<Env>;

Note

The minimum version of mysql2 required for Hyperdrive is 3.13.0.

Now, deploy your Worker:

npx wrangler deploy

If you successfully receive the list of tables from your database when you access your deployed Worker, your Hyperdrive has now been configured to securely connect to a private database using Cloudflare Tunnel and Cloudflare Access.

Troubleshooting

If you encounter issues when setting up your Hyperdrive configuration with tunnels to a private database, consider these common solutions, in addition to general troubleshooting steps for Hyperdrive:

  • Ensure your database is configured to use TLS (SSL). Hyperdrive requires TLS (SSL) to connect.

Was this helpful?

YesNo

On this page

Connect to a private database using Tunn·续 - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/hyperdrive/configuration/connect-to-private-database/#page","headline":"Connect to a private database using Tunnel","description":"Securely connect Hyperdrive to private databases using Cloudflare Tunnel and Access.","url":"https://developers.cloudflare.com/hyperdrive/configuration/connect-to-private-database/","inLanguage":"en","image":"https://developers.cloudflare.com/hyperdrive/configuration/connect-to-private-database/og.png?v=f8ceb336accd279d","dateModified":"2026-10-12","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: Workers VPC provides a way to connect Hyperdrive to a private database without configuring Cloudflare Access applications or service tokens. Instead, you create a TCP VPC Service that points to your database and pass its service ID to Hyperdrive. title: Connect to a private database using Workers VPC (Recommended) image: https://developers.cloudflare.com/hyperdrive/configuration/connect-to-private-database-vpc/og.png?v=74c80cc8872d1921


Skip to content

Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/hyperdrive/llms.txt
Use this file to discover all available pages before exploring further.