Getting 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 caches 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.
Before you begin, ensure you have completed the following:
- Sign up for a Cloudflare account ↗ if you have not already.
- Install
Node.js
↗. Use a Node version manager like nvm ↗ or Volta ↗ to avoid permission issues and change Node.js versions. Wrangler requires a Node version of16.17.0
or later. - Have a publicly accessible PostgreSQL/MySQL (or compatible) database.
Before creating your Hyperdrive binding, log in with your Cloudflare account by running:
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.
Create a new project named hyperdrive-tutorial
by running:
npm create cloudflare@latest -- hyperdrive-tutorial
pnpm create cloudflare@latest hyperdrive-tutorial
yarn create cloudflare hyperdrive-tutorial
For setup, select the following options:
- For What would you like to start with?, choose
Hello World Starter
. - For Which template would you like to use?, choose
Worker only
. - 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 atsrc/index.ts
. - A
wrangler.jsonc
configuration file.wrangler.jsonc
is how yourhyperdrive-tutorial
Worker will connect to Hyperdrive.
Node.js compatibility is required for database drivers, and needs to be configured for your Workers project.
To enable both built-in runtime APIs and polyfills for your Worker or Pages project, add the nodejs_compat
compatibility flag to your Wrangler configuration file, and set your compatibility date to September 23rd, 2024 or later. This will enable Node.js compatibility for your Workers project.
{ "compatibility_flags": [ "nodejs_compat" ], "compatibility_date": "2024-09-23"}
compatibility_flags = [ "nodejs_compat" ]compatibility_date = "2024-09-23"
Hyperdrive works by connecting to your database, pooling database connections globally, and speeding up your database access through Cloudflare's network.
It will provide a secure connection string that is only accessible from your Worker which you can use to connect to your database through Hyperdrive. This means that you can use the Hyperdrive connection string with your existing drivers or ORM libraries without needing significant changes to your code.
To create your first Hyperdrive database configuration, change into the directory you just created for your Workers project:
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
ormysql
.
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 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:
npx wrangler hyperdrive create <YOUR_CONFIG_NAME> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"
mysql://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_name
Most database providers will provide a connection string you can 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:
npx wrangler hyperdrive create <YOUR_CONFIG_NAME> --connection-string="mysql://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"
If successful, the command will output your new Hyperdrive configuration:
{ "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "<example id: 57b7076f58be42419276f058a8968187>" } ]}
Copy the id
field: you will use this in the next step to make Hyperdrive accessible from your Worker script.
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>" } ]}
[[hyperdrive]]binding = "HYPERDRIVE"id = "<YOUR_DATABASE_ID>" # the ID associated with the Hyperdrive you just created
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>", "localConnectionString": "<LOCAL_DATABASE_CONNECTION_URI>" } ]}
[[hyperdrive]]binding = "HYPERDRIVE"id = "<YOUR_DATABASE_ID>" # the ID associated with the Hyperdrive you just createdlocalConnectionString = "<LOCAL_DATABASE_CONNECTION_URI>"
Once you have created a Hyperdrive configuration and bound it to your Worker, you can run a query against your database.
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:
# This should install v3.4.5 or laternpm i postgres
# This should install v3.4.5 or laterpnpm add postgres
# This should install v3.4.5 or lateryarn add postgres
With the driver installed, you can now create a Worker script that queries your database.
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 mysql2 ↗, one of the most widely used MySQL drivers.
To install mysql2
, ensure you are in the hyperdrive-tutorial
directory. Open your terminal and run the following command:
# This should install v3.13.0 or laternpm i mysql2
# This should install v3.13.0 or laterpnpm add mysql2
# This should install v3.13.0 or lateryarn add mysql2
With the driver installed, you can now create a Worker script that queries your database.
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 recommendedimport 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 connection using the Postgres.js driver (or any supported driver, ORM or query builder) // with the Hyperdrive credentials. These credentials are only accessible from your Worker. 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 not using array types in your Postgres schema, // disabling this will save you an extra round-trip every time you connect. fetch_types: false, });
try { // Sample query const results = await sql`SELECT * FROM pg_tables`;
// Clean up the client after the response is returned, before the Worker is killed 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:
- Creates a new database client configured to connect to your database via Hyperdrive, using the Hyperdrive connection string.
- Initiates a query via
await sql
that outputs all tables (user and system created) in the database (as an example query). - Returns the response as JSON to the client.
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:
// mysql2 v3.13.0 or later is requiredimport { createConnection } from 'mysql2/promise';
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 connection using the mysql2 driver (or any support driver, ORM or query builder) // with the Hyperdrive credentials. These credentials are only accessible from your Worker. const connection = await createConnection({ host: env.DB_HOST, user: env.DB_USER, password: env.DB_PASSWORD, database: env.DB_NAME, port: env.DB_PORT
// The following line is needed for mysql2 compatibility with Workers // mysql2 uses eval() to optimize result parsing for rows with > 100 columns // Configure mysql2 to use static parsing instead of eval() parsing with disableEval disableEval: true });
try{ // Sample query const [results, fields] = await connection.query( 'SHOW tables;' );
// Clean up the client after the response is returned, before the Worker is killed ctx.waitUntil(connection.end());
// Return result rows as JSON return new Response(JSON.stringify({ results, fields }), { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, }); } 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:
- Creates a new database client configured to connect to your database via Hyperdrive, using the Hyperdrive connection string.
- Initiates a query via
await connection.query
that outputs all tables (user and system created) in the database (as an example query). - Returns the response as JSON to the client.
You can now deploy your Worker to make your project accessible on the Internet. To deploy your Worker, run:
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.
- Learn more about how Hyperdrive works.
- How to configure query caching.
- Troubleshooting common issues when connecting a database to Hyperdrive.
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 ↗.
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Products
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark