Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

node-postgres (pg)

最終更新 Markdown で表示Agent セットアップ

node-postgres(pg)は、Node.js アプリケーション向けに広く使われている PostgreSQL ドライバーです。この例では、Workers アプリケーションで Cloudflare Hyperdrive と node-postgres を使う方法を示します。

node-postgres ドライバーをインストールします。

npm i pg@>8.16.3

TypeScript を使う場合は、型定義パッケージもインストールします。

npm i -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 });
		}
	},
};

役に立ちましたか?