node-postgres ↗(pg)は、Node.js アプリケーション向けに広く使われている PostgreSQL ドライバーです。この例では、Workers アプリケーションで Cloudflare Hyperdrive と node-postgres を使う方法を示します。
node-postgres ドライバーをインストールします。
npm i pg@>8.16.3yarn add pg@>8.16.3pnpm add pg@>8.16.3bun add pg@>8.16.3TypeScript を使う場合は、型定義パッケージもインストールします。
npm i -D @types/pgyarn add -D @types/pgpnpm add -D @types/pgbun add -d @types/pg必要な Node.js 互換性フラグと Hyperdrive バインディングを、wrangler.jsonc ファイルに追加します。
{
// required for database drivers to function
"compatibility_flags": [
"nodejs_compat"
],
// Set this to today's date
"compatibility_date": "2026-09-20",
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<your-hyperdrive-id-here>"
}
]
}compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-09-20"
[[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 });
}
},
};