cloudflare-hyperdrive

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare Hyperdrive

Cloudflare Hyperdrive

Status: Production Ready ✅ Last Updated: 2025-10-22 Dependencies: cloudflare-worker-base (recommended for Worker setup) Latest Versions: wrangler@4.43.0+, pg@8.13.0+, postgres@3.4.5+, mysql2@3.13.0+

状态: 生产就绪 ✅ 最后更新: 2025-10-22 依赖项: cloudflare-worker-base(Worker 搭建推荐使用) 最新版本: wrangler@4.43.0+, pg@8.13.0+, postgres@3.4.5+, mysql2@3.13.0+

Quick Start (5 Minutes)

快速开始(5分钟)

1. Create Hyperdrive Configuration

1. 创建Hyperdrive配置

bash
undefined
bash
undefined

For PostgreSQL

For PostgreSQL

npx wrangler hyperdrive create my-postgres-db
--connection-string="postgres://user:password@db-host.cloud:5432/database"
npx wrangler hyperdrive create my-postgres-db
--connection-string="postgres://user:password@db-host.cloud:5432/database"

For MySQL

For MySQL

npx wrangler hyperdrive create my-mysql-db
--connection-string="mysql://user:password@db-host.cloud:3306/database"
npx wrangler hyperdrive create my-mysql-db
--connection-string="mysql://user:password@db-host.cloud:3306/database"

Output:

Output:

✅ Successfully created Hyperdrive configuration

✅ Successfully created Hyperdrive configuration

[[hyperdrive]]

[[hyperdrive]]

binding = "HYPERDRIVE"

binding = "HYPERDRIVE"

id = "a76a99bc-7901-48c9-9c15-c4b11b559606"

id = "a76a99bc-7901-48c9-9c15-c4b11b559606"


**Save the `id` value** - you'll need it in the next step!

---

**保存`id`值**——下一步会用到!

---

2. Configure Bindings in wrangler.jsonc

2. 在wrangler.jsonc中配置绑定

Add to your
wrangler.jsonc
:
jsonc
{
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2024-09-23",
  "compatibility_flags": ["nodejs_compat"],  // REQUIRED for database drivers
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",                     // Available as env.HYPERDRIVE
      "id": "a76a99bc-7901-48c9-9c15-c4b11b559606"  // From wrangler hyperdrive create
    }
  ]
}
CRITICAL:
  • nodejs_compat
    flag is REQUIRED for all database drivers
  • binding
    is how you access Hyperdrive in code (
    env.HYPERDRIVE
    )
  • id
    is the Hyperdrive configuration ID (NOT your database ID)

将以下内容添加到你的
wrangler.jsonc
jsonc
{
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2024-09-23",
  "compatibility_flags": ["nodejs_compat"],  // REQUIRED for database drivers
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",                     // Available as env.HYPERDRIVE
      "id": "a76a99bc-7901-48c9-9c15-c4b11b559606"  // From wrangler hyperdrive create
    }
  ]
}
关键注意事项:
  • 所有数据库驱动都必须添加
    nodejs_compat
    标志
  • binding
    是你在代码中访问Hyperdrive的方式(
    env.HYPERDRIVE
  • id
    是Hyperdrive配置ID(不是你的数据库ID)

3. Install Database Driver

3. 安装数据库驱动

bash
undefined
bash
undefined

For PostgreSQL (choose one)

For PostgreSQL (choose one)

npm install pg # node-postgres (most common) npm install postgres # postgres.js (modern, minimum v3.4.5)
npm install pg # node-postgres (most common) npm install postgres # postgres.js (modern, minimum v3.4.5)

For MySQL

For MySQL

npm install mysql2 # mysql2 (minimum v3.13.0)

---
npm install mysql2 # mysql2 (minimum v3.13.0)

---

4. Query Your Database

4. 查询你的数据库

PostgreSQL with node-postgres (pg):
typescript
import { Client } from "pg";

type Bindings = {
  HYPERDRIVE: Hyperdrive;
};

export default {
  async fetch(request: Request, env: Bindings, ctx: ExecutionContext) {
    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString
    });

    await client.connect();

    try {
      const result = await client.query('SELECT * FROM users LIMIT 10');
      return Response.json({ users: result.rows });
    } finally {
      // Clean up connection AFTER response is sent
      ctx.waitUntil(client.end());
    }
  }
};
MySQL with mysql2:
typescript
import { createConnection } from "mysql2/promise";

export default {
  async fetch(request: Request, env: Bindings, ctx: ExecutionContext) {
    const connection = await createConnection({
      host: env.HYPERDRIVE.host,
      user: env.HYPERDRIVE.user,
      password: env.HYPERDRIVE.password,
      database: env.HYPERDRIVE.database,
      port: env.HYPERDRIVE.port,
      disableEval: true  // REQUIRED for Workers (eval() not supported)
    });

    try {
      const [rows] = await connection.query('SELECT * FROM users LIMIT 10');
      return Response.json({ users: rows });
    } finally {
      ctx.waitUntil(connection.end());
    }
  }
};

使用node-postgres(pg)连接PostgreSQL:
typescript
import { Client } from "pg";

type Bindings = {
  HYPERDRIVE: Hyperdrive;
};

export default {
  async fetch(request: Request, env: Bindings, ctx: ExecutionContext) {
    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString
    });

    await client.connect();

    try {
      const result = await client.query('SELECT * FROM users LIMIT 10');
      return Response.json({ users: result.rows });
    } finally {
      // Clean up connection AFTER response is sent
      ctx.waitUntil(client.end());
    }
  }
};
使用mysql2连接MySQL:
typescript
import { createConnection } from "mysql2/promise";

export default {
  async fetch(request: Request, env: Bindings, ctx: ExecutionContext) {
    const connection = await createConnection({
      host: env.HYPERDRIVE.host,
      user: env.HYPERDRIVE.user,
      password: env.HYPERDRIVE.password,
      database: env.HYPERDRIVE.database,
      port: env.HYPERDRIVE.port,
      disableEval: true  // REQUIRED for Workers (eval() not supported)
    });

    try {
      const [rows] = await connection.query('SELECT * FROM users LIMIT 10');
      return Response.json({ users: rows });
    } finally {
      ctx.waitUntil(connection.end());
    }
  }
};

5. Deploy

5. 部署

bash
npx wrangler deploy
That's it! Your Worker now connects to your existing database via Hyperdrive with:
  • ✅ Global connection pooling
  • ✅ Automatic query caching
  • ✅ Reduced latency (eliminates 7 round trips)

bash
npx wrangler deploy
完成! 你的Worker现在通过Hyperdrive连接到现有数据库,具备以下特性:
  • ✅ 全局连接池
  • ✅ 自动查询缓存
  • ✅ 低延迟(减少7次往返)

How Hyperdrive Works

Hyperdrive 工作原理

The Problem

现存问题

Connecting to traditional databases from Cloudflare's 300+ global locations presents challenges:
  1. High Latency - Multiple round trips for each connection:
    • TCP handshake (1 round trip)
    • TLS negotiation (3 round trips)
    • Database authentication (3 round trips)
    • Total: 7 round trips before you can even send a query
  2. Connection Limits - Traditional databases handle limited concurrent connections, easily exhausted by distributed traffic
从Cloudflare的300+全球节点连接传统数据库存在以下挑战:
  1. 高延迟——每次连接需要多次往返:
    • TCP握手(1次往返)
    • TLS协商(3次往返)
    • 数据库认证(3次往返)
    • 总计:发送查询前需要7次往返
  2. 连接限制——传统数据库处理并发连接的能力有限,容易被分布式流量耗尽

The Solution

解决方案

Hyperdrive solves these problems by:
  1. Edge Connection Setup - Connection handshake happens near your Worker (low latency)
  2. Connection Pooling - Pool near your database reuses connections (eliminates round trips)
  3. Query Caching - Popular queries cached at the edge (reduces database load)
Result: Single-region databases feel globally distributed.

Hyperdrive通过以下方式解决这些问题:
  1. 边缘连接建立——连接握手在Worker附近完成(低延迟)
  2. 连接池——在数据库附近复用连接(消除往返次数)
  3. 查询缓存——热门查询在边缘缓存(降低数据库负载)
结果:单区域数据库拥有全局分布式的体验。

Complete Setup Process

完整搭建流程

Step 1: Prerequisites

步骤1:前置条件

You need:
  • Cloudflare account with Workers access
  • Existing PostgreSQL (v9.0-17.x) or MySQL (v5.7-8.x) database
  • Database accessible via:
    • Public internet (with TLS/SSL enabled), OR
    • Private network (via Cloudflare Tunnel)
Important: Hyperdrive requires TLS/SSL. Ensure your database has encryption enabled.

你需要:
  • 拥有Workers访问权限的Cloudflare账户
  • 现有PostgreSQL(v9.0-17.x)或MySQL(v5.7-8.x)数据库
  • 数据库可通过以下方式访问:
    • 公网(已启用TLS/SSL),或
    • 私有网络(通过Cloudflare Tunnel)
重要提示:Hyperdrive 必须使用TLS/SSL。确保你的数据库已启用加密。

Step 2: Create Hyperdrive Configuration

步骤2:创建Hyperdrive配置

Option A: Wrangler CLI (Recommended)
bash
undefined
选项A:Wrangler CLI(推荐)
bash
undefined

PostgreSQL connection string format:

PostgreSQL connection string format:

postgres://username:password@hostname:port/database_name

postgres://username:password@hostname:port/database_name

npx wrangler hyperdrive create my-hyperdrive
--connection-string="postgres://myuser:mypassword@db.example.com:5432/mydb"
npx wrangler hyperdrive create my-hyperdrive
--connection-string="postgres://myuser:mypassword@db.example.com:5432/mydb"

MySQL connection string format:

MySQL connection string format:

mysql://username:password@hostname:port/database_name

mysql://username:password@hostname:port/database_name

npx wrangler hyperdrive create my-hyperdrive
--connection-string="mysql://myuser:mypassword@db.example.com:3306/mydb"

**Option B: Cloudflare Dashboard**

1. Go to [Hyperdrive Dashboard](https://dash.cloudflare.com/?to=/:account/workers/hyperdrive)
2. Click **Create Configuration**
3. Enter connection details:
   - Name: `my-hyperdrive`
   - Protocol: PostgreSQL or MySQL
   - Host: `db.example.com`
   - Port: `5432` (PostgreSQL) or `3306` (MySQL)
   - Database: `mydb`
   - Username: `myuser`
   - Password: `mypassword`
4. Click **Create**

**Connection String Formats:**

```bash
npx wrangler hyperdrive create my-hyperdrive
--connection-string="mysql://myuser:mypassword@db.example.com:3306/mydb"

**选项B:Cloudflare控制台**

1. 前往[Hyperdrive控制台](https://dash.cloudflare.com/?to=/:account/workers/hyperdrive)
2. 点击**创建配置**
3. 输入连接详情:
   - 名称:`my-hyperdrive`
   - 协议:PostgreSQL或MySQL
   - 主机:`db.example.com`
   - 端口:`5432`(PostgreSQL)或`3306`(MySQL)
   - 数据库:`mydb`
   - 用户名:`myuser`
   - 密码:`mypassword`
4. 点击**创建**

**连接字符串格式:**

```bash

PostgreSQL (standard)

PostgreSQL (standard)

postgres://user:password@host:5432/database
postgres://user:password@host:5432/database

PostgreSQL with SSL mode

PostgreSQL with SSL mode

postgres://user:password@host:5432/database?sslmode=require
postgres://user:password@host:5432/database?sslmode=require

MySQL

MySQL

mysql://user:password@host:3306/database
mysql://user:password@host:3306/database

With special characters in password (URL encode)

With special characters in password (URL encode)

postgres://user:p%40ssw%24rd@host:5432/database # p@ssw$rd

---
postgres://user:p%40ssw%24rd@host:5432/database # p@ssw$rd

---

Step 3: Configure Worker Bindings

步骤3:配置Worker绑定

Add Hyperdrive binding to
wrangler.jsonc
:
jsonc
{
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2024-09-23",
  "compatibility_flags": ["nodejs_compat"],
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "<your-hyperdrive-id-here>"
    }
  ]
}
Multiple Hyperdrive configs:
jsonc
{
  "hyperdrive": [
    {
      "binding": "POSTGRES_DB",
      "id": "postgres-hyperdrive-id"
    },
    {
      "binding": "MYSQL_DB",
      "id": "mysql-hyperdrive-id"
    }
  ]
}
Access in Worker:
typescript
type Bindings = {
  POSTGRES_DB: Hyperdrive;
  MYSQL_DB: Hyperdrive;
};

export default {
  async fetch(request, env: Bindings, ctx) {
    // Access different databases
    const pgClient = new Client({ connectionString: env.POSTGRES_DB.connectionString });
    const mysqlConn = await createConnection({ host: env.MYSQL_DB.host, ... });
  }
};

将Hyperdrive绑定添加到
wrangler.jsonc
jsonc
{
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2024-09-23",
  "compatibility_flags": ["nodejs_compat"],
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "<your-hyperdrive-id-here>"
    }
  ]
}
多Hyperdrive配置:
jsonc
{
  "hyperdrive": [
    {
      "binding": "POSTGRES_DB",
      "id": "postgres-hyperdrive-id"
    },
    {
      "binding": "MYSQL_DB",
      "id": "mysql-hyperdrive-id"
    }
  ]
}
在Worker中访问:
typescript
type Bindings = {
  POSTGRES_DB: Hyperdrive;
  MYSQL_DB: Hyperdrive;
};

export default {
  async fetch(request, env: Bindings, ctx) {
    // Access different databases
    const pgClient = new Client({ connectionString: env.POSTGRES_DB.connectionString });
    const mysqlConn = await createConnection({ host: env.MYSQL_DB.host, ... });
  }
};

Step 4: Install Database Driver

步骤4:安装数据库驱动

PostgreSQL Drivers:
bash
undefined
PostgreSQL驱动:
bash
undefined

Option 1: node-postgres (pg) - Most popular

Option 1: node-postgres (pg) - Most popular

npm install pg npm install @types/pg # TypeScript types
npm install pg npm install @types/pg # TypeScript types

Option 2: postgres.js - Modern, faster (minimum v3.4.5)

Option 2: postgres.js - Modern, faster (minimum v3.4.5)

npm install postgres@^3.4.5

**MySQL Drivers:**

```bash
npm install postgres@^3.4.5

**MySQL驱动:**

```bash

mysql2 (minimum v3.13.0)

mysql2 (minimum v3.13.0)

npm install mysql2

**Driver Comparison:**

| Driver | Database | Pros | Cons | Min Version |
|--------|----------|------|------|-------------|
| **pg** | PostgreSQL | Most popular, stable, well-documented | Slightly slower than postgres.js | 8.13.0+ |
| **postgres** | PostgreSQL | Faster, modern API, streaming support | Newer (less community examples) | 3.4.5+ |
| **mysql2** | MySQL | Promises, prepared statements, fast | Requires `disableEval: true` for Workers | 3.13.0+ |

---
npm install mysql2

**驱动对比:**

| 驱动 | 数据库 | 优点 | 缺点 | 最低版本 |
|--------|----------|------|------|-------------|
| **pg** | PostgreSQL | 最流行、稳定、文档完善 | 比postgres.js稍慢 | 8.13.0+ |
| **postgres** | PostgreSQL | 更快、现代API、支持流处理 | 较新(社区示例较少) | 3.4.5+ |
| **mysql2** | MySQL | 支持Promise、预处理语句、速度快 | Workers中需要设置`disableEval: true` | 3.13.0+ |

---

Step 5: Use Driver in Worker

步骤5:在Worker中使用驱动

PostgreSQL with pg (Client):
typescript
import { Client } from "pg";

export default {
  async fetch(request: Request, env: { HYPERDRIVE: Hyperdrive }, ctx: ExecutionContext) {
    // Create client for this request
    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString
    });

    await client.connect();

    try {
      // Run query
      const result = await client.query('SELECT $1::text as message', ['Hello from Hyperdrive!']);
      return Response.json(result.rows);
    } catch (error) {
      return new Response(`Database error: ${error.message}`, { status: 500 });
    } finally {
      // CRITICAL: Clean up connection after response
      ctx.waitUntil(client.end());
    }
  }
};
PostgreSQL with pg (Pool for parallel queries):
typescript
import { Pool } from "pg";

export default {
  async fetch(request: Request, env: { HYPERDRIVE: Hyperdrive }, ctx: ExecutionContext) {
    // Create pool (max 5 to stay within Workers' 6 connection limit)
    const pool = new Pool({
      connectionString: env.HYPERDRIVE.connectionString,
      max: 5  // CRITICAL: Workers limit is 6 concurrent external connections
    });

    try {
      // Run parallel queries
      const [users, posts] = await Promise.all([
        pool.query('SELECT * FROM users LIMIT 10'),
        pool.query('SELECT * FROM posts LIMIT 10')
      ]);

      return Response.json({
        users: users.rows,
        posts: posts.rows
      });
    } finally {
      ctx.waitUntil(pool.end());
    }
  }
};
PostgreSQL with postgres.js:
typescript
import postgres from "postgres";

export default {
  async fetch(request: Request, env: { HYPERDRIVE: Hyperdrive }, ctx: ExecutionContext) {
    const sql = postgres(env.HYPERDRIVE.connectionString, {
      max: 5,              // Max 5 connections (Workers limit: 6)
      fetch_types: false,  // Disable if not using array types (reduces latency)
      prepare: true        // CRITICAL: Enable prepared statements for caching
    });

    try {
      const users = await sql`SELECT * FROM users LIMIT 10`;
      return Response.json({ users });
    } finally {
      ctx.waitUntil(sql.end({ timeout: 5 }));
    }
  }
};
MySQL with mysql2:
typescript
import { createConnection } from "mysql2/promise";

export default {
  async fetch(request: Request, env: { HYPERDRIVE: Hyperdrive }, ctx: ExecutionContext) {
    const connection = await createConnection({
      host: env.HYPERDRIVE.host,
      user: env.HYPERDRIVE.user,
      password: env.HYPERDRIVE.password,
      database: env.HYPERDRIVE.database,
      port: env.HYPERDRIVE.port,
      disableEval: true  // REQUIRED: eval() not supported in Workers
    });

    try {
      const [rows] = await connection.query('SELECT * FROM users LIMIT 10');
      return Response.json({ users: rows });
    } finally {
      ctx.waitUntil(connection.end());
    }
  }
};

使用pg(Client)连接PostgreSQL:
typescript
import { Client } from "pg";

export default {
  async fetch(request: Request, env: { HYPERDRIVE: Hyperdrive }, ctx: ExecutionContext) {
    // Create client for this request
    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString
    });

    await client.connect();

    try {
      // Run query
      const result = await client.query('SELECT $1::text as message', ['Hello from Hyperdrive!']);
      return Response.json(result.rows);
    } catch (error) {
      return new Response(`Database error: ${error.message}`, { status: 500 });
    } finally {
      // CRITICAL: Clean up connection after response
      ctx.waitUntil(client.end());
    }
  }
};
使用pg(Pool)连接PostgreSQL(并行查询):
typescript
import { Pool } from "pg";

export default {
  async fetch(request: Request, env: { HYPERDRIVE: Hyperdrive }, ctx: ExecutionContext) {
    // Create pool (max 5 to stay within Workers' 6 connection limit)
    const pool = new Pool({
      connectionString: env.HYPERDRIVE.connectionString,
      max: 5  // CRITICAL: Workers limit is 6 concurrent external connections
    });

    try {
      // Run parallel queries
      const [users, posts] = await Promise.all([
        pool.query('SELECT * FROM users LIMIT 10'),
        pool.query('SELECT * FROM posts LIMIT 10')
      ]);

      return Response.json({
        users: users.rows,
        posts: posts.rows
      });
    } finally {
      ctx.waitUntil(pool.end());
    }
  }
};
使用postgres.js连接PostgreSQL:
typescript
import postgres from "postgres";

export default {
  async fetch(request: Request, env: { HYPERDRIVE: Hyperdrive }, ctx: ExecutionContext) {
    const sql = postgres(env.HYPERDRIVE.connectionString, {
      max: 5,              // Max 5 connections (Workers limit: 6)
      fetch_types: false,  // Disable if not using array types (reduces latency)
      prepare: true        // CRITICAL: Enable prepared statements for caching
    });

    try {
      const users = await sql`SELECT * FROM users LIMIT 10`;
      return Response.json({ users });
    } finally {
      ctx.waitUntil(sql.end({ timeout: 5 }));
    }
  }
};
使用mysql2连接MySQL:
typescript
import { createConnection } from "mysql2/promise";

export default {
  async fetch(request: Request, env: { HYPERDRIVE: Hyperdrive }, ctx: ExecutionContext) {
    const connection = await createConnection({
      host: env.HYPERDRIVE.host,
      user: env.HYPERDRIVE.user,
      password: env.HYPERDRIVE.password,
      database: env.HYPERDRIVE.database,
      port: env.HYPERDRIVE.port,
      disableEval: true  // REQUIRED: eval() not supported in Workers
    });

    try {
      const [rows] = await connection.query('SELECT * FROM users LIMIT 10');
      return Response.json({ users: rows });
    } finally {
      ctx.waitUntil(connection.end());
    }
  }
};

Connection Patterns

连接模式

Pattern 1: Single Connection (pg.Client)

模式1:单一连接(pg.Client)

When to use: Simple queries, single query per request
typescript
import { Client } from "pg";

const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const result = await client.query('SELECT ...');
ctx.waitUntil(client.end());
Pros: Simple, straightforward Cons: Can't run parallel queries

适用场景:简单查询、每个请求仅执行单个查询
typescript
import { Client } from "pg";

const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const result = await client.query('SELECT ...');
ctx.waitUntil(client.end());
优点:简单、直接 缺点:无法执行并行查询

Pattern 2: Connection Pool (pg.Pool)

模式2:连接池(pg.Pool)

When to use: Multiple parallel queries in single request
typescript
import { Pool } from "pg";

const pool = new Pool({
  connectionString: env.HYPERDRIVE.connectionString,
  max: 5  // CRITICAL: Stay within Workers' 6 connection limit
});

const [result1, result2] = await Promise.all([
  pool.query('SELECT ...'),
  pool.query('SELECT ...')
]);

ctx.waitUntil(pool.end());
Pros: Parallel queries, better performance Cons: Must manage max connections

适用场景:单个请求中执行多个并行查询
typescript
import { Pool } from "pg";

const pool = new Pool({
  connectionString: env.HYPERDRIVE.connectionString,
  max: 5  // CRITICAL: Stay within Workers' 6 connection limit
});

const [result1, result2] = await Promise.all([
  pool.query('SELECT ...'),
  pool.query('SELECT ...')
]);

ctx.waitUntil(pool.end());
优点:支持并行查询、性能更好 缺点:必须管理最大连接数

Pattern 3: Connection Cleanup

模式3:连接清理

CRITICAL: Always use
ctx.waitUntil()
to clean up connections AFTER response is sent:
typescript
export default {
  async fetch(request, env, ctx) {
    const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
    await client.connect();

    try {
      const result = await client.query('SELECT ...');
      return Response.json(result.rows);  // Response sent here
    } finally {
      // This runs AFTER response is sent (non-blocking)
      ctx.waitUntil(client.end());
    }
  }
};
Why
ctx.waitUntil()
?
  • Allows Worker to return response immediately
  • Connection cleanup happens in background
  • Prevents connection leaks
DON'T do this:
typescript
await client.end();  // ❌ Blocks response, adds latency

关键注意事项:始终使用
ctx.waitUntil()
在响应发送之后清理连接:
typescript
export default {
  async fetch(request, env, ctx) {
    const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
    await client.connect();

    try {
      const result = await client.query('SELECT ...');
      return Response.json(result.rows);  // Response sent here
    } finally {
      // This runs AFTER response is sent (non-blocking)
      ctx.waitUntil(client.end());
    }
  }
};
为什么使用
ctx.waitUntil()
  • 允许Worker立即返回响应
  • 连接清理在后台进行
  • 防止连接泄漏
不要这样做:
typescript
await client.end();  // ❌ Blocks response, adds latency

ORM Integration

ORM集成

Drizzle ORM (PostgreSQL)

Drizzle ORM(PostgreSQL)

1. Install dependencies:
bash
npm install drizzle-orm postgres dotenv
npm install -D drizzle-kit
2. Define schema (
src/db/schema.ts
):
typescript
import { pgTable, serial, varchar, timestamp } from "drizzle-orm/pg-core";

export const users = pgTable("users", {
  id: serial("id").primaryKey(),
  name: varchar("name", { length: 255 }).notNull(),
  email: varchar("email", { length: 255 }).notNull().unique(),
  createdAt: timestamp("created_at").defaultNow(),
});
3. Use in Worker:
typescript
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { users } from "./db/schema";

export default {
  async fetch(request, env: { HYPERDRIVE: Hyperdrive }, ctx) {
    const sql = postgres(env.HYPERDRIVE.connectionString, { max: 5 });
    const db = drizzle(sql);

    const allUsers = await db.select().from(users);

    ctx.waitUntil(sql.end());
    return Response.json({ users: allUsers });
  }
};

1. 安装依赖:
bash
npm install drizzle-orm postgres dotenv
npm install -D drizzle-kit
2. 定义Schema(
src/db/schema.ts
):
typescript
import { pgTable, serial, varchar, timestamp } from "drizzle-orm/pg-core";

export const users = pgTable("users", {
  id: serial("id").primaryKey(),
  name: varchar("name", { length: 255 }).notNull(),
  email: varchar("email", { length: 255 }).notNull().unique(),
  createdAt: timestamp("created_at").defaultNow(),
});
3. 在Worker中使用:
typescript
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { users } from "./db/schema";

export default {
  async fetch(request, env: { HYPERDRIVE: Hyperdrive }, ctx) {
    const sql = postgres(env.HYPERDRIVE.connectionString, { max: 5 });
    const db = drizzle(sql);

    const allUsers = await db.select().from(users);

    ctx.waitUntil(sql.end());
    return Response.json({ users: allUsers });
  }
};

Prisma ORM (PostgreSQL)

Prisma ORM(PostgreSQL)

1. Install dependencies:
bash
npm install prisma @prisma/client
npm install pg @prisma/adapter-pg
2. Initialize Prisma:
bash
npx prisma init
3. Define schema (
prisma/schema.prisma
):
prisma
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["driverAdapters"]
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        Int      @id @default(autoincrement())
  name      String
  email     String   @unique
  createdAt DateTime @default(now())
}
4. Generate Prisma Client:
bash
npx prisma generate --no-engine
5. Use in Worker:
typescript
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@prisma/client";
import { Pool } from "pg";

export default {
  async fetch(request, env: { HYPERDRIVE: Hyperdrive }, ctx) {
    // Create driver adapter with Hyperdrive connection
    const pool = new Pool({ connectionString: env.HYPERDRIVE.connectionString, max: 5 });
    const adapter = new PrismaPg(pool);
    const prisma = new PrismaClient({ adapter });

    const users = await prisma.user.findMany();

    ctx.waitUntil(pool.end());
    return Response.json({ users });
  }
};
IMPORTANT: Prisma requires driver adapters (
@prisma/adapter-pg
) to work with Hyperdrive.

1. 安装依赖:
bash
npm install prisma @prisma/client
npm install pg @prisma/adapter-pg
2. 初始化Prisma:
bash
npx prisma init
3. 定义Schema(
prisma/schema.prisma
):
prisma
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["driverAdapters"]
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        Int      @id @default(autoincrement())
  name      String
  email     String   @unique
  createdAt DateTime @default(now())
}
4. 生成Prisma Client:
bash
npx prisma generate --no-engine
5. 在Worker中使用:
typescript
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@prisma/client";
import { Pool } from "pg";

export default {
  async fetch(request, env: { HYPERDRIVE: Hyperdrive }, ctx) {
    // Create driver adapter with Hyperdrive connection
    const pool = new Pool({ connectionString: env.HYPERDRIVE.connectionString, max: 5 });
    const adapter = new PrismaPg(pool);
    const prisma = new PrismaClient({ adapter });

    const users = await prisma.user.findMany();

    ctx.waitUntil(pool.end());
    return Response.json({ users });
  }
};
重要提示:Prisma需要使用驱动适配器(
@prisma/adapter-pg
)才能与Hyperdrive配合使用。

Local Development

本地开发

Option 1: Environment Variable (Recommended)

选项1:环境变量(推荐)

Set
CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING>
environment variable:
bash
undefined
设置
CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING>
环境变量:
bash
undefined

If your binding is named "HYPERDRIVE"

If your binding is named "HYPERDRIVE"

export CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE="postgres://user:password@localhost:5432/local_db"
export CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE="postgres://user:password@localhost:5432/local_db"

Start local dev server

Start local dev server

npx wrangler dev

**Benefits:**
- No credentials in wrangler.jsonc
- Safe to commit configuration files
- Different devs can use different local databases

---
npx wrangler dev

**优点:**
- wrangler.jsonc中不包含凭证
- 配置文件可安全提交到版本控制
- 不同开发者可使用不同的本地数据库

---

Option 2: localConnectionString in wrangler.jsonc

选项2:在wrangler.jsonc中设置localConnectionString

jsonc
{
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "production-hyperdrive-id",
      "localConnectionString": "postgres://user:password@localhost:5432/local_db"
    }
  ]
}
Caution: Don't commit real credentials to version control!

jsonc
{
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "production-hyperdrive-id",
      "localConnectionString": "postgres://user:password@localhost:5432/local_db"
    }
  ]
}
注意:不要将真实凭证提交到版本控制!

Option 3: Remote Development

选项3:远程开发

Connect to production database during local development:
bash
npx wrangler dev --remote
Warning: This uses your PRODUCTION database. Changes cannot be undone!

本地开发时连接到生产数据库:
bash
npx wrangler dev --remote
警告:这会使用你的生产数据库。所有更改无法撤销!

Query Caching

查询缓存

What Gets Cached

缓存内容

Hyperdrive automatically caches non-mutating queries (read-only):
sql
-- ✅ Cached
SELECT * FROM articles WHERE published = true ORDER BY date DESC LIMIT 50;
SELECT COUNT(*) FROM users;
SELECT * FROM products WHERE category = 'electronics';

-- ❌ NOT Cached
INSERT INTO users (name, email) VALUES ('John', 'john@example.com');
UPDATE posts SET published = true WHERE id = 123;
DELETE FROM sessions WHERE expired = true;
SELECT LASTVAL();  -- PostgreSQL volatile function
SELECT LAST_INSERT_ID();  -- MySQL volatile function
Hyperdrive自动缓存非变更查询(只读):
sql
-- ✅ Cached
SELECT * FROM articles WHERE published = true ORDER BY date DESC LIMIT 50;
SELECT COUNT(*) FROM users;
SELECT * FROM products WHERE category = 'electronics';

-- ❌ NOT Cached
INSERT INTO users (name, email) VALUES ('John', 'john@example.com');
UPDATE posts SET published = true WHERE id = 123;
DELETE FROM sessions WHERE expired = true;
SELECT LASTVAL();  -- PostgreSQL volatile function
SELECT LAST_INSERT_ID();  -- MySQL volatile function

How It Works

工作原理

  1. Wire Protocol Parsing: Hyperdrive parses database protocol to differentiate mutations
  2. Automatic Detection: No configuration needed
  3. Edge Caching: Cached at Cloudflare's edge (near users)
  4. Cache Invalidation: Writes invalidate relevant cached queries
  1. 协议解析:Hyperdrive解析数据库协议以区分变更操作
  2. 自动检测:无需配置
  3. 边缘缓存:缓存存储在Cloudflare边缘节点(靠近用户)
  4. 缓存失效:写入操作会使相关缓存查询失效

Caching Optimization

缓存优化

postgres.js - Enable prepared statements:
typescript
const sql = postgres(env.HYPERDRIVE.connectionString, {
  prepare: true  // CRITICAL for caching
});
Without
prepare: true
, queries are NOT cacheable!
postgres.js - 启用预处理语句:
typescript
const sql = postgres(env.HYPERDRIVE.connectionString, {
  prepare: true  // CRITICAL for caching
});
如果不设置
prepare: true
,查询将无法被缓存!

Cache Status

缓存状态

Check if query was cached:
typescript
const response = await fetch('https://your-worker.dev/api/users');
const cacheStatus = response.headers.get('cf-cache-status');
// Values: HIT, MISS, BYPASS, EXPIRED

检查查询是否被缓存:
typescript
const response = await fetch('https://your-worker.dev/api/users');
const cacheStatus = response.headers.get('cf-cache-status');
// Values: HIT, MISS, BYPASS, EXPIRED

TLS/SSL Configuration

TLS/SSL配置

SSL Modes

SSL模式

Hyperdrive supports 3 TLS/SSL modes:
  1. require
    (default) - TLS required, basic certificate validation
  2. verify-ca
    - Verify server certificate signed by expected CA
  3. verify-full
    - Verify CA + hostname matches certificate SAN
Hyperdrive支持3种TLS/SSL模式:
  1. require
    (默认)——必须使用TLS,基础证书验证
  2. verify-ca
    ——验证服务器证书是否由可信CA签发
  3. verify-full
    ——验证CA + 主机名与证书SAN匹配

Server Certificates (verify-ca / verify-full)

服务器证书(verify-ca / verify-full)

1. Upload CA certificate:
bash
npx wrangler cert upload certificate-authority \
  --ca-cert root-ca.pem \
  --name my-ca-cert
2. Create Hyperdrive with CA:
bash
npx wrangler hyperdrive create my-db \
  --connection-string="postgres://..." \
  --ca-certificate-id <CA_CERT_ID> \
  --sslmode verify-full
1. 上传CA证书:
bash
npx wrangler cert upload certificate-authority \
  --ca-cert root-ca.pem \
  --name my-ca-cert
2. 使用CA证书创建Hyperdrive:
bash
npx wrangler hyperdrive create my-db \
  --connection-string="postgres://..." \
  --ca-certificate-id <CA_CERT_ID> \
  --sslmode verify-full

Client Certificates (mTLS)

客户端证书(mTLS)

For databases requiring client authentication:
1. Upload client certificate + key:
bash
npx wrangler cert upload mtls-certificate \
  --cert client-cert.pem \
  --key client-key.pem \
  --name my-client-cert
2. Create Hyperdrive with client cert:
bash
npx wrangler hyperdrive create my-db \
  --connection-string="postgres://..." \
  --mtls-certificate-id <CERT_PAIR_ID>

对于需要客户端认证的数据库:
1. 上传客户端证书+密钥:
bash
npx wrangler cert upload mtls-certificate \
  --cert client-cert.pem \
  --key client-key.pem \
  --name my-client-cert
2. 使用客户端证书创建Hyperdrive:
bash
npx wrangler hyperdrive create my-db \
  --connection-string="postgres://..." \
  --mtls-certificate-id <CERT_PAIR_ID>

Private Database Access (Cloudflare Tunnel)

私有数据库访问(Cloudflare Tunnel)

Connect Hyperdrive to databases in private networks (VPCs, on-premises):
1. Install cloudflared:
bash
undefined
将Hyperdrive连接到私有网络(VPC、本地)中的数据库:
1. 安装cloudflared:
bash
undefined

macOS

macOS

brew install cloudflare/cloudflare/cloudflared
brew install cloudflare/cloudflare/cloudflared

Linux

Linux


**2. Create tunnel:**
```bash
cloudflared tunnel create my-db-tunnel
3. Configure tunnel (
config.yml
):
yaml
tunnel: <TUNNEL_ID>
credentials-file: /path/to/credentials.json

ingress:
  - hostname: db.example.com
    service: tcp://localhost:5432  # Your private database
  - service: http_status:404
4. Run tunnel:
bash
cloudflared tunnel run my-db-tunnel
5. Create Hyperdrive:
bash
npx wrangler hyperdrive create my-private-db \
  --connection-string="postgres://user:password@db.example.com:5432/database"


**2. 创建隧道:**
```bash
cloudflared tunnel create my-db-tunnel
3. 配置隧道(
config.yml
):
yaml
tunnel: <TUNNEL_ID>
credentials-file: /path/to/credentials.json

ingress:
  - hostname: db.example.com
    service: tcp://localhost:5432  # Your private database
  - service: http_status:404
4. 运行隧道:
bash
cloudflared tunnel run my-db-tunnel
5. 创建Hyperdrive:
bash
npx wrangler hyperdrive create my-private-db \
  --connection-string="postgres://user:password@db.example.com:5432/database"

Critical Rules

关键规则

Always Do

必须遵守

✅ Include
nodejs_compat
in
compatibility_flags
✅ Use
ctx.waitUntil(client.end())
for connection cleanup ✅ Set
max: 5
for connection pools (Workers limit: 6) ✅ Enable TLS/SSL on your database (Hyperdrive requires it) ✅ Use prepared statements for caching (postgres.js:
prepare: true
) ✅ Set
disableEval: true
for mysql2 driver ✅ Handle errors gracefully with try/catch ✅ Use environment variables for local development connection strings ✅ Test locally with
wrangler dev
before deploying
✅ 在
compatibility_flags
中包含
nodejs_compat
✅ 使用
ctx.waitUntil(client.end())
进行连接清理 ✅ 连接池设置
max: 5
(Workers限制:6) ✅ 数据库启用TLS/SSL(Hyperdrive要求) ✅ 启用预处理语句以支持缓存(postgres.js:
prepare: true
) ✅ mysql2驱动设置
disableEval: true
✅ 使用try/catch优雅处理错误 ✅ 使用环境变量存储本地开发连接字符串 ✅ 部署前使用
wrangler dev
本地测试

Never Do

禁止操作

❌ Skip
nodejs_compat
flag (causes "No such module" errors) ❌ Use private IP addresses directly (use Cloudflare Tunnel instead) ❌ Use
await client.end()
(blocks response, use
ctx.waitUntil()
) ❌ Set connection pool max > 5 (exceeds Workers' 6 connection limit) ❌ Wrap all queries in transactions (limits connection multiplexing) ❌ Use SQL-level PREPARE/EXECUTE/DEALLOCATE (unsupported) ❌ Use advisory locks, LISTEN/NOTIFY (PostgreSQL unsupported features) ❌ Use multi-statement queries in MySQL (unsupported) ❌ Commit database credentials to version control

❌ 跳过
nodejs_compat
标志(会导致“模块不存在”错误) ❌ 直接使用私有IP地址(改用Cloudflare Tunnel) ❌ 使用
await client.end()
(阻塞响应,改用
ctx.waitUntil()
) ❌ 连接池max设置>5(超过Workers的6个连接限制) ❌ 将所有查询包裹在事务中(限制连接复用) ❌ 使用SQL级别的PREPARE/EXECUTE/DEALLOCATE(不支持) ❌ 使用 advisory locks、LISTEN/NOTIFY(PostgreSQL不支持的功能) ❌ 在MySQL中使用多语句查询(不支持) ❌ 将数据库凭证提交到版本控制

Wrangler Commands Reference

Wrangler命令参考

bash
undefined
bash
undefined

Create Hyperdrive configuration

Create Hyperdrive configuration

wrangler hyperdrive create <name> --connection-string="postgres://..."
wrangler hyperdrive create <name> --connection-string="postgres://..."

List all Hyperdrive configurations

List all Hyperdrive configurations

wrangler hyperdrive list
wrangler hyperdrive list

Get details of a configuration

Get details of a configuration

wrangler hyperdrive get <hyperdrive-id>
wrangler hyperdrive get <hyperdrive-id>

Update connection string

Update connection string

wrangler hyperdrive update <hyperdrive-id> --connection-string="postgres://..."
wrangler hyperdrive update <hyperdrive-id> --connection-string="postgres://..."

Delete configuration

Delete configuration

wrangler hyperdrive delete <hyperdrive-id>
wrangler hyperdrive delete <hyperdrive-id>

Upload CA certificate

Upload CA certificate

wrangler cert upload certificate-authority --ca-cert <file>.pem --name <name>
wrangler cert upload certificate-authority --ca-cert <file>.pem --name <name>

Upload client certificate pair

Upload client certificate pair

wrangler cert upload mtls-certificate --cert <cert>.pem --key <key>.pem --name <name>

---
wrangler cert upload mtls-certificate --cert <cert>.pem --key <key>.pem --name <name>

---

Supported Databases

支持的数据库

PostgreSQL (v9.0 - 17.x)

PostgreSQL(v9.0 - 17.x)

  • ✅ AWS RDS / Aurora
  • ✅ Google Cloud SQL
  • ✅ Azure Database for PostgreSQL
  • ✅ Neon
  • ✅ Supabase
  • ✅ PlanetScale (PostgreSQL)
  • ✅ Timescale
  • ✅ CockroachDB
  • ✅ Materialize
  • ✅ Fly.io
  • ✅ pgEdge Cloud
  • ✅ Prisma Postgres
  • ✅ AWS RDS / Aurora
  • ✅ Google Cloud SQL
  • ✅ Azure Database for PostgreSQL
  • ✅ Neon
  • ✅ Supabase
  • ✅ PlanetScale(PostgreSQL)
  • ✅ Timescale
  • ✅ CockroachDB
  • ✅ Materialize
  • ✅ Fly.io
  • ✅ pgEdge Cloud
  • ✅ Prisma Postgres

MySQL (v5.7 - 8.x)

MySQL(v5.7 - 8.x)

  • ✅ AWS RDS / Aurora
  • ✅ Google Cloud SQL
  • ✅ Azure Database for MySQL
  • ✅ PlanetScale (MySQL)
  • ✅ AWS RDS / Aurora
  • ✅ Google Cloud SQL
  • ✅ Azure Database for MySQL
  • ✅ PlanetScale(MySQL)

NOT Supported

不支持

  • ❌ SQL Server
  • ❌ MongoDB (NoSQL)
  • ❌ Oracle Database

  • ❌ SQL Server
  • ❌ MongoDB(NoSQL)
  • ❌ Oracle Database

Unsupported Features

不支持的功能

PostgreSQL

PostgreSQL

  • SQL-level prepared statements (
    PREPARE
    ,
    EXECUTE
    ,
    DEALLOCATE
    )
  • Advisory locks
  • LISTEN
    and
    NOTIFY
  • Per-session state modifications
  • SQL级预处理语句(
    PREPARE
    EXECUTE
    DEALLOCATE
  • Advisory locks
  • LISTEN
    NOTIFY
  • 会话级状态修改

MySQL

MySQL

  • Non-UTF8 characters in queries
  • USE
    statements
  • Multi-statement queries
  • Protocol-level prepared statements (
    COM_STMT_PREPARE
    )
  • COM_INIT_DB
    messages
  • Auth plugins other than
    caching_sha2_password
    or
    mysql_native_password
Workaround: For unsupported features, create a second direct client connection (without Hyperdrive).

  • 查询中的非UTF8字符
  • USE
    语句
  • 多语句查询
  • 协议级预处理语句(
    COM_STMT_PREPARE
  • COM_INIT_DB
    消息
  • caching_sha2_password
    mysql_native_password
    外的认证插件
解决方法:对于不支持的功能,创建第二个不通过Hyperdrive的直接客户端连接。

Performance Best Practices

性能最佳实践

  1. Avoid long-running transactions - Limits connection multiplexing
  2. Use prepared statements - Enables query caching (postgres.js:
    prepare: true
    )
  3. Set max: 5 for pools - Stays within Workers' 6 connection limit
  4. Disable fetch_types if not needed - Reduces latency (postgres.js)
  5. Use ctx.waitUntil() for cleanup - Non-blocking connection close
  6. Cache-friendly queries - Prefer SELECT over complex joins
  7. Index frequently queried columns - Improves query performance
  8. Monitor with Hyperdrive analytics - Track cache hit ratios and latency

  1. 避免长时间运行的事务——限制连接复用
  2. 使用预处理语句——启用查询缓存(postgres.js:
    prepare: true
  3. 连接池设置max:5——符合Workers的6个连接限制
  4. 不需要时禁用fetch_types——减少延迟(postgres.js)
  5. 使用ctx.waitUntil()清理连接——非阻塞关闭连接
  6. 使用缓存友好的查询——优先使用SELECT而非复杂连接
  7. 为频繁查询的列建立索引——提升查询性能
  8. 使用Hyperdrive分析监控——跟踪缓存命中率和延迟

Troubleshooting

故障排除

See
references/troubleshooting.md
for complete error reference with solutions.
Quick fixes:
ErrorSolution
"No such module 'node:*'"Add
nodejs_compat
to compatibility_flags
"TLS not supported by database"Enable SSL/TLS on your database
"Connection refused"Check firewall rules, allow public internet or use Tunnel
"Failed to acquire connection"Use
ctx.waitUntil()
for cleanup, avoid long transactions
"Code generation from strings disallowed"Set
disableEval: true
in mysql2 config
"Bad hostname"Verify DNS resolves, check for typos
"Invalid database credentials"Check username/password (case-sensitive)

完整的错误参考及解决方案请查看
references/troubleshooting.md
快速修复:
错误解决方案
"No such module 'node:*'"在compatibility_flags中添加
nodejs_compat
"TLS not supported by database"在数据库上启用SSL/TLS
"Connection refused"检查防火墙规则,允许公网访问或使用Tunnel
"Failed to acquire connection"使用
ctx.waitUntil()
清理连接,避免长时间事务
"Code generation from strings disallowed"在mysql2配置中设置
disableEval: true
"Bad hostname"验证DNS解析,检查拼写错误
"Invalid database credentials"检查用户名/密码(区分大小写)

Metrics and Analytics

指标与分析

View Hyperdrive metrics in the dashboard:
  1. Go to Hyperdrive Dashboard
  2. Select your configuration
  3. Click Metrics tab
Available Metrics:
  • Query count
  • Cache hit ratio (hit vs miss)
  • Query latency (p50, p95, p99)
  • Connection latency
  • Query bytes / result bytes
  • Error rate

在控制台查看Hyperdrive指标:
  1. 前往Hyperdrive控制台
  2. 选择你的配置
  3. 点击指标标签
可用指标:
  • 查询次数
  • 缓存命中率(命中vs未命中)
  • 查询延迟(p50、p95、p99)
  • 连接延迟
  • 查询字节数/结果字节数
  • 错误率

Migration Strategies

迁移策略

From Direct Database Connection

从直接数据库连接迁移

Before (direct connection):
typescript
const client = new Client({
  host: 'db.example.com',
  user: 'myuser',
  password: 'mypassword',
  database: 'mydb',
  port: 5432
});
After (with Hyperdrive):
typescript
const client = new Client({
  connectionString: env.HYPERDRIVE.connectionString
});
Benefits:
  • ✅ 7 round trips eliminated
  • ✅ Query caching enabled
  • ✅ Connection pooling automatic
  • ✅ Global performance boost

迁移前(直接连接):
typescript
const client = new Client({
  host: 'db.example.com',
  user: 'myuser',
  password: 'mypassword',
  database: 'mydb',
  port: 5432
});
迁移后(使用Hyperdrive):
typescript
const client = new Client({
  connectionString: env.HYPERDRIVE.connectionString
});
优点:
  • ✅ 消除7次往返
  • ✅ 启用查询缓存
  • ✅ 自动连接池
  • ✅ 全局性能提升

From D1 to Hyperdrive

从D1迁移到Hyperdrive

When to migrate:
  • Need PostgreSQL/MySQL features (JSON types, full-text search, etc.)
  • Existing database with data
  • Multi-region read replicas
  • Advanced indexing strategies
Keep D1 if:
  • Building new Cloudflare-native app
  • SQLite features sufficient
  • No existing database to migrate
  • Want simpler serverless setup

迁移场景:
  • 需要PostgreSQL/MySQL的功能(JSON类型、全文搜索等)
  • 已有带数据的数据库
  • 多区域只读副本
  • 高级索引策略
继续使用D1的场景:
  • 构建全新Cloudflare原生应用
  • SQLite功能足够
  • 没有需要迁移的现有数据库
  • 想要更简单的无服务器设置

Credential Rotation

凭证轮换

Option 1: Create new Hyperdrive config
bash
undefined
选项1:创建新的Hyperdrive配置
bash
undefined

Create new config with new credentials

Create new config with new credentials

wrangler hyperdrive create my-db-v2 --connection-string="postgres://..."
wrangler hyperdrive create my-db-v2 --connection-string="postgres://..."

Update wrangler.jsonc to use new ID

Update wrangler.jsonc to use new ID

Deploy gradually (no downtime)

Deploy gradually (no downtime)

Delete old config when migration complete

Delete old config when migration complete


**Option 2: Update existing config**
```bash
wrangler hyperdrive update <id> --connection-string="postgres://new-credentials@..."
Best practice: Use separate Hyperdrive configs for staging and production.


**选项2:更新现有配置**
```bash
wrangler hyperdrive update <id> --connection-string="postgres://new-credentials@..."
最佳实践:为 staging 和 production 使用独立的Hyperdrive配置。

Examples

示例

See
templates/
directory for complete working examples:
  • postgres-basic.ts
    - Simple query with pg.Client
  • postgres-pool.ts
    - Parallel queries with pg.Pool
  • postgres-js.ts
    - Using postgres.js driver
  • mysql2-basic.ts
    - MySQL with mysql2 driver
  • drizzle-postgres.ts
    - Drizzle ORM integration
  • drizzle-mysql.ts
    - Drizzle ORM with MySQL
  • prisma-postgres.ts
    - Prisma ORM integration

查看
templates/
目录获取完整的可用示例:
  • postgres-basic.ts
    ——使用pg.Client的简单查询
  • postgres-pool.ts
    ——使用pg.Pool的并行查询
  • postgres-js.ts
    ——使用postgres.js驱动
  • mysql2-basic.ts
    ——使用mysql2驱动连接MySQL
  • drizzle-postgres.ts
    ——Drizzle ORM集成
  • drizzle-mysql.ts
    ——Drizzle ORM连接MySQL
  • prisma-postgres.ts
    ——Prisma ORM集成

References

参考资料


Last Updated: 2025-10-22 Package Versions: wrangler@4.43.0+, pg@8.13.0+, postgres@3.4.5+, mysql2@3.13.0+ Production Tested: Based on official Cloudflare documentation and community examples

最后更新: 2025-10-22 包版本: wrangler@4.43.0+, pg@8.13.0+, postgres@3.4.5+, mysql2@3.13.0+ 生产环境测试: 基于Cloudflare官方文档和社区示例