node-postgres ↗(pg)是 Node.js 应用中广泛使用的 PostgreSQL 驱动。本示例演示如何在 Workers 应用中将 node-postgres 与 Cloudflare Hyperdrive 配合使用。
安装 node-postgres 驱动:
npm i pg@>8.16.3yarn add pg@>8.16.3pnpm add pg@>8.16.3bun add pg@>8.16.3若使用 TypeScript,安装类型包:
npm i -D @types/pgyarn add -D @types/pgpnpm add -D @types/pgbun add -d @types/pg在 wrangler.jsonc 中添加所需的 Node.js 兼容性标志和 Hyperdrive 绑定:
在 wrangler.jsonc 中添加 Node.js 兼容性标志和 Hyperdrive 绑定(binding):
{
// required for database drivers to function
"compatibility_flags": [
"nodejs_compat"
],
// Set this to today's date
"compatibility_date": "2026-08-17",
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<your-hyperdrive-id-here>"
}
]
}compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-17"
[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"创建新的 Client 实例并传入 Hyperdrive connectionString:
// filepath: src/index.ts
import { Client } from "pg";
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
// Create a new client instance for each request. Hyperdrive maintains the
// underlying database connection pool, so creating a new client is fast.
const client = new Client({
connectionString: env.HYPERDRIVE.connectionString,
});
try {
// Connect to the database
await client.connect();
// Perform a simple query
const result = await client.query("SELECT * FROM pg_tables");
return Response.json({
success: true,
result: result.rows,
});
} catch (error: any) {
console.error("Database error:", error.message);
return new Response("Internal error occurred", { status: 500 });
}
},
};