name: cloudflare-hyperdrive description: Cloudflare Hyperdrive 用于连接 Workers 到数据库,提供连接池和缓存。适用于 PostgreSQL/MySQL、Drizzle/Prisma,或遇到连接池错误、TLS 问题、连接拒绝时使用。
关键词:hyperdrive, cloudflare hyperdrive, workers hyperdrive, postgres workers, mysql workers, connection pooling, query caching, node-postgres, pg, postgres.js, mysql2, drizzle hyperdrive, prisma hyperdrive, workers rds, workers aurora, workers neon, workers supabase, database acceleration, hybrid architecture, cloudflare tunnel database, wrangler hyperdrive, hyperdrive bindings, local development hyperdrive license: MIT metadata: version: “2.0.0” last_verified: “2025-11-18” production_tested: true token_savings: “~58%” errors_prevented: 6 templates_included: 0 references_included: 1
Cloudflare Hyperdrive
状态: 生产就绪 ✅ | 最后验证: 2025-11-18
什么是 Hyperdrive?
连接 Workers 到现有 PostgreSQL/MySQL 数据库:
- 全局连接池
- 查询缓存
- 降低延迟
- 支持 node-postgres、postgres.js、mysql2
快速开始 (5 分钟)
1. 创建 Hyperdrive 配置
bunx wrangler hyperdrive create my-db \
--connection-string="postgres://user:pass@host:5432/database"
保存 id!
2. 配置绑定
{
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2024-09-23",
"compatibility_flags": ["nodejs_compat"], // 必需!
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<ID_FROM_STEP_1>"
}
]
}
3. 安装驱动
bun add pg # 或 postgres,或 mysql2
4. 查询数据库
import { Client } from 'pg';
export default {
async fetch(request, env, ctx) {
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const result = await client.query('SELECT * FROM users LIMIT 10');
await client.end();
return Response.json(result.rows);
}
};
加载 references/setup-guide.md 获取完整指南。
关键规则
始终要做 ✅
- 启用 nodejs_compat 标志 (必需!)
- 使用 env.HYPERDRIVE.connectionString (不是原始数据库字符串)
- 查询后关闭连接
- 显式处理错误
- 使用连接池 (内置)
- 本地测试 使用 wrangler dev
- 监控查询性能
- 使用预编译语句
- 启用查询缓存 (自动)
- 安全连接字符串 (使用密钥)
绝不要做 ❌
- 绝不要跳过 nodejs_compat (驱动无法工作)
- 绝不要在 Workers 中使用原始数据库连接字符串
- 绝不要保持连接打开 (连接池耗尽)
- 绝不要跳过错误处理 (数据库可能失败)
- 绝不要在代码中硬编码凭据
- 绝不要超过连接限制
- 绝不要使用 eval/Function (在 Workers 中被阻止)
- 绝不要为生产数据库跳过 TLS
- 绝不要使用阻塞查询 (Worker 超时)
- 绝不要向用户暴露数据库错误
数据库驱动
PostgreSQL (node-postgres)
import { Client } from 'pg';
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const result = await client.query('SELECT * FROM users');
await client.end();
PostgreSQL (postgres.js)
import postgres from 'postgres';
const sql = postgres(env.HYPERDRIVE.connectionString);
const users = await sql`SELECT * FROM users`;
MySQL
import mysql from 'mysql2/promise';
const connection = await mysql.createConnection(env.HYPERDRIVE.connectionString);
const [rows] = await connection.execute('SELECT * FROM users');
await connection.end();
与 Drizzle ORM 配合使用
import { drizzle } from 'drizzle-orm/node-postgres';
import { Client } from 'pg';
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const db = drizzle(client);
const users = await db.select().from(usersTable);
await client.end();
常见使用场景
使用场景 1: 只读查询
export default {
async fetch(request, env, ctx) {
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const users = await client.query('SELECT * FROM users WHERE active = true');
await client.end();
return Response.json(users.rows);
}
};
使用场景 2: 参数化查询
const userId = new URL(request.url).searchParams.get('id');
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const result = await client.query(
'SELECT * FROM users WHERE id = $1',
[userId]
);
await client.end();
使用场景 3: 事务
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
try {
await client.query('BEGIN');
await client.query('UPDATE accounts SET balance = balance - 100 WHERE id = $1', [1]);
await client.query('UPDATE accounts SET balance = balance + 100 WHERE id = $1', [2]);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
await client.end();
}
支持的数据库
PostgreSQL:
- Amazon RDS
- Amazon Aurora
- Neon
- Supabase
- Railway
- Render
- DigitalOcean
- 任何 PostgreSQL 11+
MySQL:
- Amazon RDS
- Amazon Aurora
- PlanetScale
- 任何 MySQL 5.7+
官方文档
- Hyperdrive 概述: https://developers.cloudflare.com/hyperdrive/
- 开始使用: https://developers.cloudflare.com/hyperdrive/get-started/
- 配置: https://developers.cloudflare.com/hyperdrive/configuration/
捆绑资源
参考 (references/):
setup-guide.md- 完整设置指南 (创建配置、绑定、查询)connection-pooling.md- 连接池配置和最佳实践query-caching.md- 查询缓存策略和优化drizzle-integration.md- Drizzle ORM 集成模式prisma-integration.md- Prisma ORM 集成模式supported-databases.md- 支持的 PostgreSQL 和 MySQL 提供商的完整列表tls-ssl-setup.md- TLS/SSL 安全连接配置troubleshooting.md- 常见问题和解决方案wrangler-commands.md- Hyperdrive 的完整 wrangler CLI 命令
模板 (templates/):
postgres-basic.ts- 使用 node-postgres 的基本 PostgreSQLpostgres-js.ts- 使用 postgres.js 驱动的 PostgreSQLpostgres-pool.ts- 使用连接池的 PostgreSQLmysql2-basic.ts- 使用 mysql2 驱动的 MySQLdrizzle-postgres.ts- 使用 Drizzle ORM 的 PostgreSQLdrizzle-mysql.ts- 使用 Drizzle ORM 的 MySQLprisma-postgres.ts- 使用 Prisma ORM 的 PostgreSQLlocal-dev-setup.sh- 本地开发设置脚本wrangler-hyperdrive-config.jsonc- Wrangler 配置示例
有问题?遇到问题?
- 查看
references/setup-guide.md获取完整设置 - 验证 nodejs_compat 标志已启用
- 确保使用 env.HYPERDRIVE.connectionString
- 检查连接是否正确关闭