Skip to content

Commit dc75ae6

Browse files
committed
Fix Hyperdrive overview and get started for MySQL and free tier
1 parent d2f955c commit dc75ae6

File tree

4 files changed

+225
-73
lines changed

4 files changed

+225
-73
lines changed

src/content/docs/hyperdrive/get-started.mdx

Lines changed: 147 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ sidebar:
55
order: 2
66
---
77

8-
import { Render, PackageManagers } from "~/components";
8+
import { Render, PackageManagers, Tabs, TabItem } from "~/components";
99

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

@@ -19,19 +19,19 @@ This guide will instruct you through:
1919
- Creating a [Cloudflare Worker](/workers/) and binding it to your Hyperdrive configuration.
2020
- Establishing a database connection from your Worker to a public database.
2121

22-
## Prerequisites
23-
24-
:::note[Workers Paid plan required]
22+
:::note
2523

26-
Hyperdrive is available to all users on the [Workers Paid plan](/workers/platform/pricing/#workers).
24+
Hyperdrive currently works with PostgreSQL, MySQL and compatible databases. This includes CockroachDB and Materialize (which are PostgreSQL-compatible), and MariaDB and Planetscale (which are MySQL compatible).
2725

2826
:::
2927

30-
To continue:
28+
## Prerequisites
29+
30+
Before you begin, ensure you have completed the following:
3131

3232
1. Sign up for a [Cloudflare account](https://dash.cloudflare.com/sign-up/workers-and-pages) if you have not already.
33-
2. Install [`Node.js`](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm). Use a Node version manager like [Volta](https://volta.sh/) or [nvm](https://github.com/nvm-sh/nvm) to avoid permission issues and change Node.js versions. [Wrangler](/workers/wrangler/install-and-update/) requires a Node version of `16.17.0` or later.
34-
3. Have **a publicly accessible PostgreSQL (or PostgreSQL compatible) database**. Cloudflare recommends [Neon](https://neon.tech/) if you do not have an existing database. Read the [Neon documentation](https://neon.tech/docs/introduction) to create your first database.
33+
2. Install [`Node.js`](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm). Use a Node version manager like [nvm](https://github.com/nvm-sh/nvm) or [Volta](https://volta.sh/) to avoid permission issues and change Node.js versions. [Wrangler](/workers/wrangler/install-and-update/) requires a Node version of `16.17.0` or later.
34+
3. Have **a publicly accessible** PostgreSQL/MySQL (or compatible) database.
3535

3636
## 1. Log in
3737

@@ -76,46 +76,49 @@ This will create a new `hyperdrive-tutorial` directory. Your new `hyperdrive-tut
7676

7777
### Enable Node.js compatibility
7878

79-
[Node.js compatibility](/workers/runtime-apis/nodejs/) is required for database drivers, including Postgres.js, and needs to be configured for your Workers project.
79+
[Node.js compatibility](/workers/runtime-apis/nodejs/) is required for database drivers, and needs to be configured for your Workers project.
8080

8181
<Render file="nodejs_compat" product="workers" />
8282

8383
## 3. Connect Hyperdrive to a database
8484

85-
:::note
86-
87-
Hyperdrive currently works with PostgreSQL and PostgreSQL compatible databases, including CockroachDB and Materialize.
85+
Hyperdrive works by connecting to your database, pooling database connections globally and speeding up your database access through Cloudflare's network.
8886

89-
Support for other database engines, including MySQL, is on the roadmap.
90-
91-
:::
92-
93-
Hyperdrive works by connecting to your database.
87+
It will provide a secure connection string that is only accessible from your Worker, that you can use to connect to your database through Hyperdrive.
88+
This means that you can use the Hyperdrive connection string with your existing drivers or ORM libraries without needing significant changes to your code.
9489

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

9792
```sh
9893
cd hyperdrive-tutorial
9994
```
10095

101-
:::note
102-
103-
Support for the new `hyperdrive` commands in the wrangler CLI requires a wrangler version of `3.10.0` or later. You can use `npx wrangler@latest` to always ensure you are using the latest version of Wrangler.
104-
105-
:::
106-
10796
To create your first Hyperdrive, you will need:
10897

10998
- The IP address (or hostname) and port of your database.
11099
- The database username (for example, `hyperdrive-demo`).
111100
- The password associated with that username.
112-
- The name of the database you want Hyperdrive to connect to. For example, `postgres`.
101+
- The name of the database you want Hyperdrive to connect to. For example, `postgres` or `mysql`.
113102

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

116-
```txt
117-
postgres://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_name
118-
```
105+
<Tabs>
106+
<TabItem label="PostgreSQL">
107+
```txt
108+
109+
postgres://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_name
110+
111+
```
112+
</TabItem>
113+
<TabItem label="MySQL">
114+
```txt
115+
116+
mysql://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_name
117+
118+
```
119+
</TabItem>
120+
121+
</Tabs>
119122

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

@@ -126,7 +129,7 @@ npx wrangler hyperdrive create <YOUR_CONFIG_NAME> --connection-string="postgres:
126129
```
127130

128131
:::note[Manage caching]
129-
If you wish to disable caching, pass the flag `--caching-disabled`.
132+
By default, Hyperdrive will cache query results. If you wish to disable caching, pass the flag `--caching-disabled`.
130133

131134
Alternatively, you can use the `--max-age` flag to specify the maximum duration (in seconds) for which items should persist in the cache, before they are evicted. Default value is 60 seconds.
132135

@@ -137,14 +140,13 @@ If successful, the command will output your new Hyperdrive configuration:
137140

138141
```json
139142
{
140-
"hyperdrive": [
141-
{
142-
"binding": "HYPERDRIVE",
143+
"hyperdrive": [
144+
{
145+
"binding": "HYPERDRIVE",
143146
"id": "<example id: 57b7076f58be42419276f058a8968187>"
144-
}
145-
]
147+
}
148+
]
146149
}
147-
148150
```
149151

150152
Copy the `id` field: you will use this in the next step to make Hyperdrive accessible from your Worker script.
@@ -155,15 +157,19 @@ Hyperdrive will attempt to connect to your database with the provided credential
155157

156158
:::
157159

158-
159160
## 4. Bind your Worker to Hyperdrive
160161

161162
<Render file="create-hyperdrive-binding" product="hyperdrive" />
162163

163164
## 5. Run a query against your database
164165

166+
Once you have created a Hyperdrive configuration and bound it to your Worker, you can run a query against your database.
167+
165168
### Install a database driver
166169

170+
<Tabs>
171+
<TabItem label="PostgreSQL">
172+
167173
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](https://github.com/porsager/postgres), one of the most widely used PostgreSQL drivers.
168174

169175
To install `postgres`, ensure you are in the `hyperdrive-tutorial` directory. Open your terminal and run the following command:
@@ -172,8 +178,24 @@ To install `postgres`, ensure you are in the `hyperdrive-tutorial` directory. Op
172178

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

181+
</TabItem>
182+
<TabItem label="MySQL">
183+
184+
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](https://github.com/sidorares/node-mysql2), one of the most widely used MySQL drivers.
185+
186+
To install `mysql2`, ensure you are in the `hyperdrive-tutorial` directory. Open your terminal and run the following command:
187+
188+
<PackageManagers pkg="mysql2" comment="This should install v3.13.0 or later" />
189+
190+
With the driver installed, you can now create a Worker script that queries your database.
191+
192+
</TabItem>
193+
</Tabs>
194+
175195
### Write a Worker
176196

197+
<Tabs>
198+
<TabItem label="PostgreSQL">
177199
After you have set up your database, you will run a SQL query from within your Worker.
178200

179201
Go to your `hyperdrive-tutorial` Worker and open the `index.ts` file.
@@ -194,32 +216,23 @@ export interface Env {
194216

195217
export default {
196218
async fetch(request, env, ctx): Promise<Response> {
197-
console.log(JSON.stringify(env));
198-
// Create a database client that connects to your database via Hyperdrive.
199-
//
200-
// Hyperdrive generates a unique connection string you can pass to
201-
// supported drivers, including node-postgres, Postgres.js, and the many
202-
// ORMs and query builders that use these drivers.
203-
const sql = postgres(
204-
env.HYPERDRIVE.connectionString,
205-
{
206-
// Workers limit the number of concurrent external connections, so be sure to limit
207-
// the size of the local connection pool that postgres.js may establish.
208-
max: 5,
209-
210-
// If you are using array types in your Postgres schema, it is necessary to fetch
211-
// type information to correctly de/serialize them. However, if you are not using
212-
// those, disabling this will save you an extra round-trip every time you connect.
213-
fetch_types: false,
214-
},
215-
);
219+
// Create a connection using the Postgres.js driver (or any support driver, ORM or query builder)
220+
// with the Hyperdrive credentials. These credentials are only accessible from your Worker.
221+
const sql = postgres(env.HYPERDRIVE.connectionString, {
222+
// Workers limit the number of concurrent external connections, so be sure to limit
223+
// the size of the local connection pool that postgres.js may establish.
224+
max: 5,
225+
226+
// If you are not using array types in your Postgres schema,
227+
// disabling this will save you an extra round-trip every time you connect.
228+
fetch_types: false,
229+
});
216230

217231
try {
218-
// Test query
232+
// Sample query
219233
const results = await sql`SELECT * FROM pg_tables`;
220234

221-
// Clean up the client, ensuring we don't kill the worker before that is
222-
// completed.
235+
// Clean up the client after the response is returned, before the Worker is killed
223236
ctx.waitUntil(sql.end());
224237

225238
// Return result rows as JSON
@@ -241,6 +254,83 @@ Upon receiving a request, the code above does the following:
241254
2. Initiates a query via `await sql` that outputs all tables (user and system created) in the database (as an example query).
242255
3. Returns the response as JSON to the client.
243256

257+
</TabItem>
258+
<TabItem label="MySQL">
259+
After you have set up your database, you will run a SQL query from within your Worker.
260+
261+
Go to your `hyperdrive-tutorial` Worker and open the `index.ts` file.
262+
263+
The `index.ts` file is where you configure your Worker's interactions with Hyperdrive.
264+
265+
Populate your `index.ts` file with the following code:
266+
267+
```typescript
268+
// mysql2 v3.13.0 or later is required
269+
import { createConnection } from 'mysql2/promise';
270+
271+
export interface Env {
272+
// If you set another name in the Wrangler config file as the value for 'binding',
273+
// replace "HYPERDRIVE" with the variable name you defined.
274+
HYPERDRIVE: Hyperdrive;
275+
}
276+
277+
export default {
278+
async fetch(request, env, ctx): Promise<Response> {
279+
280+
// Create a connection using the mysql2 driver (or any support driver, ORM or query builder)
281+
// with the Hyperdrive credentials. These credentials are only accessible from your Worker.
282+
const connection = await createConnection({
283+
host: env.DB_HOST,
284+
user: env.DB_USER,
285+
password: env.DB_PASSWORD,
286+
database: env.DB_NAME,
287+
port: env.DB_PORT
288+
289+
// The following line is needed for mysql2 compatibility with Workers
290+
// mysql2 uses eval() to optimize result parsing for rows with > 100 columns
291+
// Configure mysql2 to use static parsing instead of eval() parsing with disableEval
292+
disableEval: true
293+
});
294+
295+
try{
296+
// Sample query
297+
const [results, fields] = await connection.query(
298+
'SHOW tables;'
299+
);
300+
301+
// Clean up the client after the response is returned, before the Worker is killed
302+
ctx.waitUntil(connection.end());
303+
304+
// Return result rows as JSON
305+
return new Response(JSON.stringify({ results, fields }), {
306+
headers: {
307+
'Content-Type': 'application/json',
308+
'Access-Control-Allow-Origin': '*',
309+
},
310+
});
311+
}
312+
catch(e){
313+
console.error(e);
314+
return Response.json(
315+
{ error: e instanceof Error ? e.message : e },
316+
{ status: 500 },
317+
);
318+
}
319+
320+
},
321+
} satisfies ExportedHandler<Env>;
322+
323+
```
324+
325+
Upon receiving a request, the code above does the following:
326+
327+
1. Creates a new database client configured to connect to your database via Hyperdrive, using the Hyperdrive connection string.
328+
2. Initiates a query via `await connection.query` that outputs all tables (user and system created) in the database (as an example query).
329+
3. Returns the response as JSON to the client.
330+
331+
</TabItem>
332+
</Tabs>
333+
244334
## 6. Deploy your Worker
245335

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

0 commit comments

Comments
 (0)