Skip to content

Get started

Hyperdrive accelerates access to your existing databases from Cloudflare Workers, making even single-region databases feel globally distributed.

By maintaining a connection pool to your database within Cloudflare's network, Hyperdrive reduces seven round-trips to your database before you can even send a query: the TCP handshake (1x), TLS negotiation (3x), and database authentication (3x).

Hyperdrive understands the difference between read and write queries to your database, and can cache the most common read queries, improving performance and reducing load on your origin database.

This guide will instruct you through:

  • Creating your first Hyperdrive configuration.
  • Creating a Cloudflare Worker and binding it to your Hyperdrive configuration.
  • Establishing a database connection from your Worker to a public database.

Prerequisites

To continue:

  1. Sign up for a Cloudflare account if you have not already.
  2. Install Node.js. Use a Node version manager like Volta or nvm to avoid permission issues and change Node.js versions. Wrangler requires a Node version of 16.17.0 or later.
  3. Have a publicly accessible PostgreSQL (or PostgreSQL compatible) database. Cloudflare recommends Neon if you do not have an existing database. Read the Neon documentation to create your first database.

1. Log in

Before creating your Hyperdrive binding, log in with your Cloudflare account by running:

Terminal window
npx wrangler login

You will be directed to a web page asking you to log in to the Cloudflare dashboard. After you have logged in, you will be asked if Wrangler can make changes to your Cloudflare account. Scroll down and select Allow to continue.

2. Create a Worker

Create a new project named hyperdrive-tutorial by running:

Terminal window
npm create cloudflare@latest -- hyperdrive-tutorial

For setup, select the following options:

  • For What would you like to start with?, choose Hello World example.
  • For Which template would you like to use?, choose Hello World Worker.
  • For Which language do you want to use?, choose TypeScript.
  • For Do you want to use git for version control?, choose Yes.
  • For Do you want to deploy your application?, choose No (we will be making some changes before deploying).

This will create a new hyperdrive-tutorial directory. Your new hyperdrive-tutorial directory will include:

  • A "Hello World" Worker at src/index.ts.
  • A wrangler.toml configuration file. wrangler.toml is how your hyperdrive-tutorial Worker will connect to Hyperdrive.

3. Connect Hyperdrive to a database

Hyperdrive works by connecting to your database.

To create your first Hyperdrive database configuration, change into the directory you just created for your Workers project:

Terminal window
cd hyperdrive-tutorial

To create your first Hyperdrive, you will need:

  • The IP address (or hostname) and port of your database.
  • The database username (for example, hyperdrive-demo).
  • 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:

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 connection, run the wrangler command, replacing the placeholder values passed to the --connection-string flag with the values of your existing database:

Terminal window
npx wrangler hyperdrive create <YOUR_CONFIG_NAME> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"

If successful, the command will output your new Hyperdrive configuration:

{
"id": "<example id: 57b7076f58be42419276f058a8968187>",
"name": "YOUR_CONFIG_NAME",
"origin": {
"host": "YOUR_DATABASE_HOST",
"port": 5432,
"database": "DATABASE",
"user": "DATABASE_USER"
},
"caching": {
"disabled": false
}
}

Copy the id field: you will use this in the next step to make Hyperdrive accessible from your Worker script.

4. Bind your Worker to Hyperdrive

You must create a binding for your Worker to connect to your Hyperdrive configuration. Bindings allow your Workers to access resources, like D1, on the Cloudflare developer platform. You create bindings by updating your wrangler.toml file.

To bind your Hyperdrive configuration to your Worker, add the following to the end of your wrangler.toml file:

[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<YOUR_DATABASE_ID>" # the ID associated with the Hyperdrive you just created

Specifically:

  • The value (string) you set for the name (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>.

5. Run a query against your database

Install a database driver

To connect to your database, you will need a database driver which allows you to authenticate and query your database. For this tutorial, you will use Postgres.js, one of the most widely used PostgreSQL drivers.

To install postgres, ensure you are in the hyperdrive-tutorial directory. Open your terminal and run the following command:

Terminal window
# This should install v3.4.5 or later
npm i postgres

With the driver installed, you can now create a Worker script that queries your database.

Write a Worker

After you have set up your database, you will run a SQL query from within your Worker.

Go to your hyperdrive-tutorial Worker and open the index.ts file.

The index.ts file is where you configure your Worker's interactions with Hyperdrive.

Populate your index.ts file with the following code:

// Postgres.js 3.4.5 or later is recommended
import postgres from "postgres";
export interface Env {
// If you set another name in wrangler.toml as the value for 'binding',
// replace "HYPERDRIVE" with the variable name you defined.
HYPERDRIVE: Hyperdrive;
}
export default {
async fetch(request, env, ctx): Promise<Response> {
console.log(JSON.stringify(env));
// Create a database client that connects to your 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);
try {
// Test query
const results = 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(results);
} catch (e) {
console.error(e);
return Response.json(
{ error: e instanceof Error ? e.message : e },
{ status: 500 },
);
}
},
} satisfies ExportedHandler<Env>;

Upon receiving a request, the code above does the following:

  1. Creates a new database client configured to connect to your database via Hyperdrive, using the Hyperdrive connection string.
  2. Initiates a query via await sql that outputs all tables (user and system created) in the database (as an example query).
  3. Returns the response as JSON to the client.

6. Deploy your Worker

You can now deploy your Worker to make your project accessible on the Internet. To deploy your Worker, run:

Terminal window
npx wrangler deploy
# Outputs: https://hyperdrive-tutorial.<YOUR_SUBDOMAIN>.workers.dev

You can now visit the URL for your newly created project to query your live database.

For example, if the URL of your new Worker is hyperdrive-tutorial.<YOUR_SUBDOMAIN>.workers.dev, accessing https://hyperdrive-tutorial.<YOUR_SUBDOMAIN>.workers.dev/ will send a request to your Worker that queries your database directly.

By finishing this tutorial, you have created a Hyperdrive configuration, a Worker to access that database and deployed your project globally.

Next steps

If you have any feature requests or notice any bugs, share your feedback directly with the Cloudflare team by joining the Cloudflare Developers community on Discord.