Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
d7eb2e1
[Hyperdrive] drafting custom cert support for Hyperdrive
thomasgauvin Mar 24, 2025
d578ae1
corrections
thomasgauvin Mar 28, 2025
7a2aeb5
wip
thomasgauvin Apr 8, 2025
1bb1afc
add changelog
thomasgauvin Apr 8, 2025
2eb045c
adjust per comments
thomasgauvin Apr 8, 2025
6131158
add note on wrangler version
thomasgauvin Apr 8, 2025
a4409e7
add troubleshooting guides for ssl certs
thomasgauvin Apr 8, 2025
a5bcb69
change changelog entry date
thomasgauvin Apr 8, 2025
28638fa
Update src/content/docs/hyperdrive/configuration/tls-ssl-certificates…
thomasgauvin Apr 9, 2025
8442a7b
Update src/content/docs/hyperdrive/configuration/tls-ssl-certificates…
thomasgauvin Apr 9, 2025
a637925
PCX review
Oxyjun Apr 9, 2025
a244fa6
add drivers and orms to hyperdrive docs
thomasgauvin Apr 30, 2025
d490626
Apply suggestions from code review
Oxyjun May 1, 2025
9297e73
Apply suggestions from code review
Oxyjun May 1, 2025
28676b2
Specifying product when rendering partials
Oxyjun May 1, 2025
721b41e
Importing Render components
Oxyjun May 1, 2025
0410c7b
Fixing invalid links
Oxyjun May 1, 2025
03cb1cc
adjust per discord feedback
thomasgauvin May 2, 2025
249d6d6
more nits
thomasgauvin May 2, 2025
02df4be
Pushing changes to Postgres Drizzle ORM tutorial
Oxyjun May 6, 2025
0517e7b
Editing MySQL version of the tutorial
Oxyjun May 7, 2025
955db1e
Adding note about when to run the optional
Oxyjun May 8, 2025
ed882f4
Removing outdated redirects to avoid breaking
Oxyjun May 8, 2025
f1444e2
Adding missing redirects.
Oxyjun May 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ Validate that you can connect to your database from Workers and make queries.

Use Postgres.js to send a test query to validate that the connection has been successful.

<Render file="use-postgresjs-to-make-query" product="hyperdrive" />
<Render file="use-postgres-js-to-make-query" product="hyperdrive" />

Now, deploy your Worker:

Expand Down
66 changes: 3 additions & 63 deletions src/content/docs/hyperdrive/examples/connect-to-mysql/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,7 @@ npx wrangler hyperdrive create my-first-hyperdrive --connection-string="mysql://

The command above will output the ID of your Hyperdrive, which you will need to set in the [Wrangler configuration file](/workers/wrangler/configuration/) for your Workers project:

<WranglerConfig>

```toml
# required for database drivers to function
compatibility_flags = ["nodejs_compat"]
compatibility_date = "2024-09-23"

[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"
```

</WranglerConfig>
<Render file="hyperdrive-node-compatibility-requirement" product="hyperdrive" />

This will allow Hyperdrive to generate a dynamic connection string within your Worker that you can pass to your existing database driver. Refer to [Driver examples](#driver-examples) to learn how to set up a database driver with Hyperdrive.

Expand Down Expand Up @@ -105,57 +93,9 @@ The following Workers code shows you how to use [mysql2](https://github.com/sido

### `mysql`

Install the `mysql` driver:
The following Workers code shows you how to use [mysql](https://github.com/mysqljs/mysql) with Hyperdrive.

```sh
npm install mysql
```

**Ensure you have `compatibility_flags` and `compatibility_date` set in your [Wrangler configuration file](/workers/wrangler/configuration/)** as shown below:

<Render file="nodejs-compat-wrangler-toml" product="workers" />

Create a new connection and pass the Hyperdrive parameters:

```ts
import { createConnection } from "mysql";

export interface Env {
HYPERDRIVE: Hyperdrive;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
const result = await new Promise<any>((resolve) => {
const connection = createConnection({
host: env.HYPERDRIVE.host,
user: env.HYPERDRIVE.user,
password: env.HYPERDRIVE.password,
database: env.HYPERDRIVE.database,
port: env.HYPERDRIVE.port,
});

connection.connect((error: { message: string }) => {
if (error) {
throw new Error(error.message);
}

connection.query("SHOW tables;", [], (error, rows, fields) => {
connection.end();

resolve({ fields, rows });
});
});
});

return new Response(JSON.stringify(result), {
headers: {
"Content-Type": "application/json",
},
});
},
} satisfies ExportedHandler<Env>;
```
<Render file="use-mysql-to-make-query" product="hyperdrive" />

## Identify connections from Hyperdrive

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,4 @@ With a database user, password, database endpoint (hostname and port), and datab
## 3. Create a database configuration

<Render file="create-hyperdrive-config-mysql" />
<Render file="create-hyperdrive-config-mysql-next-steps" />
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@ To connect to a private Azure Database for MySQL instance, refer to [Connect to
## 2. Create a database configuration

<Render file="create-hyperdrive-config-mysql" />
<Render file="create-hyperdrive-config-mysql-next-steps" />
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ With the username, password, public IP address and (optional) database name (def
## 2. Create a database configuration

<Render file="create-hyperdrive-config-mysql" />
<Render file="create-hyperdrive-config-mysql-next-steps" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
type: overview
pcx_content_type: navigation
title: Database Providers
hideChildren: false
sidebar:
order: 5
group:
hideIndex: true
---

import { DirectoryListing } from "~/components";

<DirectoryListing />
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,11 @@ With the host, database name, username and password, you can now create a Hyperd
## 2. Create a database configuration

<Render file="create-hyperdrive-config-mysql" />

:::note

When connecting to a Planetscale database with Hyperdrive, you should use a driver like [node-postgres (pg)](/hyperdrive/examples/connect-to-postgres/postgres-drivers-and-libraries/node-postgres/) or [Postgres.js](/hyperdrive/examples/connect-to-postgres/postgres-drivers-and-libraries/postgres-js/) to connect directly to the underlying database instead of the [Planetscale serverless driver](https://planetscale.com/docs/tutorials/planetscale-serverless-driver). Hyperdrive is optimized for database access for Workers and will perform global connection pooling and fast query routing by connecting directly to your database.

:::

<Render file="create-hyperdrive-config-mysql-next-steps" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
---
pcx_content_type: example
title: Drizzle ORM
sidebar:
order: 3
meta:
title: Using Drizzle ORM with Hyperdrive for MySQL
---

import { Render } from "~/components";

[Drizzle ORM](https://orm.drizzle.team/) is a lightweight TypeScript ORM with a focus on type safety. This example demonstrates how to use Drizzle ORM with MySQL via Cloudflare Hyperdrive in a Workers application.

## Prerequisites

- A Cloudflare account with Workers access
- A MySQL database
- A [Hyperdrive configuration to your MySQL database](/hyperdrive/get-started/#3-connect-hyperdrive-to-a-database)

## 1. Install Drizzle

Install the Drizzle ORM and its dependencies such as the [mysql2](https://github.com/sidorares/node-mysql2) driver:

```sh
# mysql2 v3.13.0 or later is required
npm i drizzle-orm mysql2 dotenv
npm i -D drizzle-kit tsx @types/node
```

Add the required Node.js compatibility flags and Hyperdrive binding to your `wrangler.jsonc` file:

<Render file="hyperdrive-node-compatibility-requirement" />

## 2. Configure Drizzle

### 2.1 Define a schema

With Drizzle ORM, we define the schema in TypeScript rather than writing raw SQL. Here is how to define a `users` table:

```ts
// src/schema.ts
import { mysqlTable, int, varchar, timestamp } from "drizzle-orm/mysql-core";

export const users = mysqlTable("users", {
id: int("id").primaryKey().autoincrement(),
name: varchar("name", { length: 255 }).notNull(),
email: varchar("email", { length: 255 }).notNull().unique(),
createdAt: timestamp("created_at").defaultNow(),
});
```

### 2.2 Connect Drizzle ORM to the database with Hyperdrive

Use your the credentials of your Hyperdrive configuration for your database when using the Drizzle ORM within your Worker project as shown:

```ts
// src/db/schema.ts

import { drizzle } from "drizzle-orm/mysql2";
import { createConnection } from "mysql2";
import { users } from "./db/schema";

export default {
async fetch(request, env, ctx): Promise<Response> {
// Create a connection using the mysql2 driver with the Hyperdrive credentials (only accessible from your Worker).
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,
});

// Create the Drizzle client with the mysql2 driver connection
const db = drizzle(connection);

// Sample query to get all users
const allUsers = await db.select().from(users);

return Response.json(allUsers);
},
} satisfies ExportedHandler<Env>;
```

### 2.3 Configure Drizzle-Kit for migrations (optional)

You can generate and run SQL migrations on your database based on your schema using Drizzle Kit CLI. Refer to [Drizzle ORM docs](https://orm.drizzle.team/docs/get-started/mysql-new) for additional guidance.

1. Create a `.env` file and add your database connection string. The Drizzle Kit CLI will use this connection string to create and apply the migrations.

```toml
# Replace with your direct database connection string
DATABASE_URL='mysql://user:[email protected]/database-name'
```

2. Create a `drizzle.config.ts` file in the root of your project to configure Drizzle Kit and add the following content:

```ts
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './src/db/schema.ts',
dialect: 'mysql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});
```

3. Generate the migration file for your database according to your schema files and apply the migrations to your database.

```bash
npx drizzle-kit generate
npx drizzle-kit migrate
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
pcx_content_type: navigation
title: Libraries and Drivers
sidebar:
order: 8
group:
hideIndex: true
---

import { DirectoryListing } from "~/components";

<DirectoryListing />
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
pcx_content_type: example
title: mysql
sidebar:
order: 2
meta:
title: Using mysql driver with Hyperdrive
---

import { Render } from "~/components";

The [mysql](https://github.com/mysqljs/mysql) package is a MySQL driver for Node.js.
This example demonstrates how to use it with Cloudflare Workers and Hyperdrive.

<Render file="use-mysql-to-make-query" product="hyperdrive" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
pcx_content_type: example
title: mysql2
sidebar:
order: 1
---

import { Render } from "~/components";

The [mysql2](https://github.com/sidorares/node-mysql2) package is a modern MySQL driver for Node.js with better performance and built-in Promise support.
This example demonstrates how to use it with Cloudflare Workers and Hyperdrive.

<Render file="use-mysql2-to-make-query" product="hyperdrive" />
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,7 @@ npx wrangler hyperdrive create my-first-hyperdrive --connection-string="postgres

The command above will output the ID of your Hyperdrive, which you will need to set in the [Wrangler configuration file](/workers/wrangler/configuration/) for your Workers project:

<WranglerConfig>

```toml
# required for database drivers to function
compatibility_flags = ["nodejs_compat"]
compatibility_date = "2024-09-23"

[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"
```

</WranglerConfig>
<Render file="hyperdrive-node-compatibility-requirement" product="hyperdrive" />

This will allow Hyperdrive to generate a dynamic connection string within your Worker that you can pass to your existing database driver. Refer to [Driver examples](#driver-examples) to learn how to set up a database driver with Hyperdrive.

Expand Down Expand Up @@ -84,57 +72,13 @@ The following examples show you how to:

The following Workers code shows you how to use [Postgres.js](https://github.com/porsager/postgres) with Hyperdrive.

<Render file="use-postgresjs-to-make-query" product="hyperdrive" />
<Render file="use-postgres-js-to-make-query" product="hyperdrive" />

### node-postgres / pg

Install the `node-postgres` driver:

```sh
npm install pg
```

**Ensure you have `compatibility_flags` and `compatibility_date` set in your [Wrangler configuration file](/workers/wrangler/configuration/)** as shown below:

<Render file="nodejs-compat-wrangler-toml" product="workers" />

Create a new `Client` instance and pass the Hyperdrive parameters:

```ts
import { Client } from "pg";

export interface Env {
// If you set another name in the Wrangler configuration 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> {
const client = new Client({
connectionString: env.HYPERDRIVE.connectionString,
});

try {
// Connect to your database
await client.connect();

// A very simple test query
const result = await client.query({ text: "SELECT * FROM pg_tables" });

// Clean up the client, ensuring we don't kill the worker before that is
// completed.
ctx.waitUntil(client.end());

// Return result rows as JSON
return Response.json({ result: result });
} catch (e) {
console.log(e);
return Response.json({ error: e.message }, { status: 500 });
}
},
} satisfies ExportedHandler<Env>;
```
<Render file="use-node-postgres-to-make-query" product="hyperdrive" />

## Identify connections from Hyperdrive

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,4 @@ With a database user, password, database endpoint (hostname and port) and databa
## 3. Create a database configuration

<Render file="create-hyperdrive-config" />
<Render file="create-hyperdrive-config-next-steps" />
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@ To connect to a private Azure Database for PostgreSQL instance, refer to [Connec
## 2. Create a database configuration

<Render file="create-hyperdrive-config" />
<Render file="create-hyperdrive-config-next-steps" />
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ By default, the CockroachDB cloud enables connections from the public Internet (
## 2. Create a database configuration

<Render file="create-hyperdrive-config" />
<Render file="create-hyperdrive-config-next-steps" />
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ With the connection string, you can now create a Hyperdrive database configurati
## 2. Create a database configuration

<Render file="create-hyperdrive-config" />
<Render file="create-hyperdrive-config-next-steps" />

:::note
If you see a DNS-related error, it is possible that the DNS for your vendor's database has not yet been propagated. Try waiting 10 minutes before retrying the operation. Refer to [DigitalOcean support page](https://docs.digitalocean.com/support/why-does-my-domain-fail-to-resolve/) for more information.
Expand Down
Loading
Loading