This example shows you how to connect Hyperdrive to a Fly PostgreSQL database instance.

## 1. Allow Hyperdrive access

You can connect Hyperdrive to any existing Fly database by:

1. Allocating a public IP address to your Fly database instance
2. Configuring an external service
3. Deploying the configuration
4. Obtain the connection string, which is used to connect the database to Hyperdrive.

1) Run the following command to [allocate a public IP address](https://fly.io/docs/postgres/connecting/connecting-external/#allocate-an-ip-address).

   ```txt
   fly ips allocate-v6 --app <pg-app-name>
   ```

   Note

   Cloudflare recommends using IPv6, but some Internet service providers may not support IPv6. In this case, [you can allocate an IPv4 address](https://fly.io/docs/postgres/connecting/connecting-with-flyctl/).

2) [Configure an external service](https://fly.io/docs/postgres/connecting/connecting-external/#configure-an-external-service) by modifying the contents of your `fly.toml` file. Run the following command to download the `fly.toml` file.

   ```txt
   fly config save --app <pg-app-name>
   ```

   Then, replace the `services` and `services.ports` section of the file with the following `toml` snippet:

   ```toml
   [[services]]
     internal_port = 5432 # Postgres instance
     protocol = "tcp"


   [[services.ports]]
     handlers = ["pg_tls"]
     port = 5432
   ```

3) [Deploy the new configuration](https://fly.io/docs/postgres/connecting/connecting-external/#deploy-with-the-new-configuration).

4) [Obtain the connection string](https://fly.io/docs/postgres/connecting/connecting-external/#adapting-the-connection-string), which is in the form of:

   ```txt
   postgres://{username}:{password}@{public-hostname}:{port}/{database}?options
   ```

## 2. Create a database configuration

To configure Hyperdrive, you will need:

* The IP address (or hostname) and port of your database.
* The database username (for example, `hyperdrive-demo`) you configured in a previous step.
* The password associated with that username.
* The name of the database you want Hyperdrive to connect to. For example, `postgres`.

Hyperdrive accepts the combination of these parameters in the common connection string format used by database drivers:

```txt
postgres://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_name
```

Most database providers will provide a connection string you can directly copy-and-paste directly into Hyperdrive.

To create a Hyperdrive configuration with the [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/install-and-update/), open your terminal and run the following command. Replace \<NAME\_OF\_HYPERDRIVE\_CONFIG> with a name for your Hyperdrive configuration and paste the connection string provided from your database host, or replace `user`, `password`, `HOSTNAME_OR_IP_ADDRESS`, `port`, and `database_name` placeholders with those specific to your database:

```sh
npx wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"
```

Note

Hyperdrive will attempt to connect to your database with the provided credentials to verify they are correct before creating a configuration. If you encounter an error when attempting to connect, refer to Hyperdrive's [troubleshooting documentation](https://developers.cloudflare.com/hyperdrive/observability/troubleshooting/) to debug possible causes.

This command outputs a binding for the [Wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/configuration/):

* wrangler.jsonc

  ```jsonc
  {
    "name": "hyperdrive-example",
    "main": "src/index.ts",
    "compatibility_date": "2024-08-21",
    "compatibility_flags": [
      "nodejs_compat"
    ],
    "hyperdrive": [
      {
        "binding": "HYPERDRIVE",
        "id": "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"
      }
    ]
  }
  ```

* wrangler.toml

  ```toml
  name = "hyperdrive-example"
  main = "src/index.ts"
  compatibility_date = "2024-08-21"
  compatibility_flags = ["nodejs_compat"]


  # Pasted from the output of `wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string=[...]` above.
  [[hyperdrive]]
  binding = "HYPERDRIVE"
  id = "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"
  ```

Install the driver:

```sh
npm install postgres
```

Copy the below Worker code, which passes the connection string generated from `env.HYPERDRIVE.connectionString` directly to the driver.

```ts
import postgres from "postgres";


export interface Env {
  // If you set another name in the Wrangler config file as the value for 'binding',
  // replace "HYPERDRIVE" with the variable name you defined.
  HYPERDRIVE: Hyperdrive;
}


export default {
  async fetch(request, env, ctx): Promise<Response> {
    // Create a database client that connects to our database via Hyperdrive
    // Hyperdrive generates a unique connection string you can pass to
    // supported drivers, including node-postgres, Postgres.js, and the many
    // ORMs and query builders that use these drivers.
    const sql = postgres(
            env.HYPERDRIVE.connectionString,
            {
                // Workers limit the number of concurrent external connections, so be sure to limit
                // the size of the local connection pool that postgres.js may establish.
                max: 5,


                // If you are using array types in your Postgres schema, it is necessary to fetch
                // type information to correctly de/serialize them. However, if you are not using
                // those, disabling this will save you an extra round-trip every time you connect.
                fetch_types: false,
            },
        );


    try {
      // Test query
      const result = await sql`SELECT * FROM pg_tables;`;


      // Returns result rows as JSON
      return Response.json({ result: result });
    } catch (e: any) {
      console.log(e);
      return Response.json({ error: e.message }, { status: 500 });
    }
  },
} satisfies ExportedHandler<Env>;
```

## Next steps

* Learn more about [How Hyperdrive Works](https://developers.cloudflare.com/hyperdrive/configuration/how-hyperdrive-works/).
* Refer to the [troubleshooting guide](https://developers.cloudflare.com/hyperdrive/observability/troubleshooting/) to debug common issues.
* Understand more about other [storage options](https://developers.cloudflare.com/workers/platform/storage-options/) available to Cloudflare Workers.
