Skip to content

非公式 / UnofficialCloudflare, Inc. 非提携。アカウント情報は入力しないでください。Not affiliated with Cloudflare, Inc. Do not enter Cloudflare credentials here.Official docsこのサイトについてプライバシー

Supabase

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

Supabase ↗ は、オープンソースの Firebase 代替であり、リアルタイム機能、データベースバックアップ、拡張機能を備えた PostgreSQL データベースサービスです。Supabase を使うと、PostgreSQL データベースをすばやく用意してアプリケーションを構築できます。

Supabase クライアントのセットアップ

Supabase と連携する手順は次のとおりです。

  1. 接続先となる既存の Supabase データベースが必要です。Supabase データベースを作成する ↗ か、既存のデータベースを Supabase に接続してデータを読み込む ↗ ことができます。

  2. 次のクエリで countries テーブルを作成します。Supabase ダッシュボードでテーブルを作成する方法は 2 つあります。

    • テーブルエディターを使うと、スプレッドシートに近い操作で Postgres を設定できます。
    • または SQL エディター ↗ を使います。
    CREATE TABLE countries (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL
    );
  3. 作成したテーブルにデータを挿入します。次のコマンドを実行して、テーブルに国名を追加します。

    INSERT INTO countries (name) VALUES ('United States');
    INSERT INTO countries (name) VALUES ('Canada');
    INSERT INTO countries (name) VALUES ('The Netherlands');
  4. Worker に Supabase データベースの認証情報を設定します。

    Supabase の URL と anon キーをシークレットとして Worker に追加します。Supabase Dashboard ↗ の Settings > API から取得し、Wrangler でシークレットとして追加します。

    # Add the Supabase URL as a secret
    npx wrangler secret put SUPABASE_URL
    # When prompted, paste your Supabase project URL
    
    # Add the Supabase anon key as a secret
    npx wrangler secret put SUPABASE_KEY
    # When prompted, paste your Supabase anon/public key
  5. Worker で @supabase/supabase-js ドライバーをインストールし、データベースに接続してデータの操作を始めます。

    npm i @supabase/supabase-js
  6. 次の例は、Worker から Supabase データベースへクエリする方法です。Supabase への接続に必要な認証情報は、シークレットとして Worker に追加済みです。

    import { createClient } from "@supabase/supabase-js";
    
    export default {
    	async fetch(request, env) {
    		const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_KEY);
    		const { data, error } = await supabase.from("countries").select("*");
    		if (error) throw error;
    		return new Response(JSON.stringify(data), {
    			headers: {
    				"Content-Type": "application/json",
    			},
    		});
    	},
    };

Supabase の詳細は、Supabase の公式ドキュメント ↗ を参照してください。

Hyperdrive で Supabase に接続する場合は、背後の Postgres データベースに直接接続します。Workers からサーバーサイドでアクセスするデータベースクエリでは、これが最も低いレイテンシになります。Hyperdrive で Supabase に接続する手順は次のとおりです。

1. Hyperdrive からのアクセスを許可する

プロジェクト作成時に設定された Postgres ユーザーとして、既存の任意の Supabase データベースに Hyperdrive を接続できます。 別のユーザーを Hyperdrive 用に作る場合は、SQL Editor ↗ で次のコマンドを実行します。

データベースのエンドポイントは database settings ページ ↗ で確認できます。

データベースユーザー、パスワード、データベースエンドポイント(ホスト名とポート)、データベース名(デフォルト: postgres)が揃えば、Hyperdrive を設定できます。

2. データベース設定を作成する

Hyperdrive を設定するには、次の情報が必要です。

  • データベースの IP アドレス(またはホスト名)とポート。
  • 前の手順で設定したデータベースのユーザー名(例: hyperdrive-demo)。
  • そのユーザー名に対応するパスワード。
  • Hyperdrive が接続するデータベース名。例: postgres。

Hyperdrive は、これらのパラメーターを組み合わせた、データベースドライバーで一般的な接続文字列形式を受け付けます。

postgres://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_name

ほとんどのデータベースプロバイダーは、Hyperdrive にそのままコピー&ペーストできる接続文字列を提供します。

Cloudflare ダッシュボードで Hyperdrive 設定を作成する手順は次のとおりです。

  1. Cloudflare ダッシュボードで Hyperdrive ページを開きます。

    公式ダッシュボードで Hyperdrive を開く ↗
  2. Create Configuration を選択します。

  3. 接続文字列を含め、フォームに入力します。

  4. Create を選択します。

Wrangler CLI で Hyperdrive 設定を作成する手順は次のとおりです。

  1. ターミナルを開き、次のコマンドを実行します。<NAME_OF_HYPERDRIVE_CONFIG> を Hyperdrive 設定の名前に置き換え、データベースホストから提供された接続文字列を貼り付けるか、user、password、HOSTNAME_OR_IP_ADDRESS、port、database_name のプレースホルダーをデータベース固有の値に置き換えます。

    npx wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"
  2. このコマンドは、Wrangler 設定ファイル 向けのバインディングを出力します。

    {
    	"$schema": "./node_modules/wrangler/config-schema.json",
    	"name": "hyperdrive-example",
    	"main": "src/index.ts",
    	// Set this to today's date
    	"compatibility_date": "2026-11-14",
    	"compatibility_flags": [
    		"nodejs_compat"
    	],
    	// Pasted from the output of `wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string=[...]` above.
    	"hyperdrive": [
    		{
    			"binding": "HYPERDRIVE",
    			"id": "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"
    		}
    	]
    }
    "$schema" = "./node_modules/wrangler/config-schema.json"
    name = "hyperdrive-example"
    main = "src/index.ts"
    # Set this to today's date
    compatibility_date = "2026-11-14"
    compatibility_flags = [ "nodejs_compat" ]
    
    [[hyperdrive]]
    binding = "HYPERDRIVE"
    id = "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"

3. Worker から Hyperdrive を使う

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-11-14",
	"hyperdrive": [
		{
			"binding": "HYPERDRIVE",
			"id": "<your-hyperdrive-id-here>"
		}
	]
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-11-14"

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

次のステップ

役に立ちましたか?