🚗

Remix + Cloudflare Pages + D1を使ってみる

2025/01/22に公開

本記事ではRemix + Cloudfalre Pages + D1を組み合わせて、データを取得・表示する方法を記載します。

Remixプロジェクトを作成

まず、以下のコマンドでd1-sampleという名前のプロジェクトを作成します。

npm create cloudflare@latest -- d1-sample --framework=remix

次に、プロジェクトディレクトリに移動して開発を開始します。

cd d1-sample
npm run dev

データベースの作成

Wranglerのインストール

Cloudflare Workers用のCLIツールであるWranglerをインストールします。

npm install -g wrangler

https://developers.cloudflare.com/workers/wrangler/

D1データベースの作成

以下のコマンドで、sample-dbという名前のデータベースを作成します。

wrangler d1 create sample-db

成功すると、以下のようにバインディング設定が表示されます。

✅ Successfully created DB 'sample-db' in region WNAM
Created your new D1 database.

[[d1_databases]]
binding = "DB"
database_name = "sample-db"
database_id = "f713be39-9ca2-4731-aa55-1540f5e422d9"

この設定をwrangler.tomlに記載します。

D1データベースへのクエリ実行

テーブルの作成とデータ登録

プロジェクトのルートディレクトリにschema.sqlファイルを作成し、以下の内容を記述します。

DROP TABLE IF EXISTS Customers;
CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT);
INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name');

ローカル環境での実行とテスト

以下のコマンドでデータベースを初期化します。

npx wrangler d1 execute sample-db --local --file=./schema.sql

データが正しく登録されているか確認するには、次のコマンドを実行します。

npx wrangler d1 execute prod-d1-tutorial --local --command="SELECT * FROM Customers"

結果として、以下のようにデータが表示されます。

 ⛅️ wrangler 3.104.0
--------------------

🌀 Executing on local database sample-db (f713be39-9ca2-4731-aa55-1540f5e422d9) from .wrangler/state/v3/d1:
🌀 To execute on your remote database, add a --remote flag to your wrangler command.
🚣 1 command executed successfully.
┌────────────┬─────────────────────┬───────────────────┐
│ CustomerId │ CompanyName         │ ContactName       │
├────────────┼─────────────────────┼───────────────────┤
│ 1          │ Alfreds Futterkiste │ Maria Anders      │
├────────────┼─────────────────────┼───────────────────┤
│ 4          │ Around the Horn     │ Thomas Hardy      │
├────────────┼─────────────────────┼───────────────────┤
│ 11         │ Bs Beverages        │ Victoria Ashworth │
├────────────┼─────────────────────┼───────────────────┤
│ 13         │ Bs Beverages        │ Random Name       │
└────────────┴─────────────────────┴───────────────────┘

RemixからD1にクエリを実行

以下は、Remixを使用してD1データベースからデータを取得するコード例です。

  • バインディングは、LoaderFunctionに渡されるcontext.envパラメータで取得できます。
  • 以下の例では、context.env.DB経由でD1 Workers Binding APIメソッドにアクセスします。
app/routes/_index.tsx
import type { LoaderFunction } from "@remix-run/cloudflare";
import { json } from "@remix-run/cloudflare";
import { useLoaderData } from "@remix-run/react";

type Customer = {
  CustomerID: number;
  CompanyName: string;
  ContactName: string;
};

interface Env {
  DB: D1Database;
}

export const loader: LoaderFunction = async ({ context }) => {
  const env = context.cloudflare.env as Env;

  const { results } = await env.DB.prepare("SELECT * FROM Customers LIMIT 5").all<Customer>();
  return json(results);
};

export default function Index() {
  const customers = useLoaderData<typeof loader>() as Customer[];
  return (
    <div className="flex h-screen items-center justify-center">
      <ul>
        {customers.map((customer) => (
          <li key={customer.CustomerID}>
            {customer.ContactName}
          </li>
        ))}
      </ul>
    </div>
  );
}

ローカル環境で動作を確認します。

npm run dev

以下のように、データベースの内容がブラウザに表示されるはずです。

Cloudflareにデプロイ

スキーマの反映

本番環境のデータベースにスキーマを反映するには、以下を実行します。

npx wrangler d1 execute sample-db --remote --file=./schema.sql

データの確認は次のコマンドで行います。

npx wrangler d1 execute sample-db --remote --command="SELECT * FROM Customers"

 ⛅️ wrangler 3.104.0
--------------------

🌀 Executing on remote database sample-db (f713be39-9ca2-4731-aa55-1540f5e422d9):
🌀 To execute on your local development database, remove the --remote flag from your wrangler command.
🚣 Executed 1 command in 0.251ms
┌────────────┬─────────────────────┬───────────────────┐
│ CustomerId │ CompanyName         │ ContactName       │
├────────────┼─────────────────────┼───────────────────┤
│ 1          │ Alfreds Futterkiste │ Maria Anders      │
├────────────┼─────────────────────┼───────────────────┤
│ 4          │ Around the Horn     │ Thomas Hardy      │
├────────────┼─────────────────────┼───────────────────┤
│ 11         │ Bs Beverages        │ Victoria Ashworth │
├────────────┼─────────────────────┼───────────────────┤
│ 13         │ Bs Beverages        │ Random Name       │
└────────────┴─────────────────────┴───────────────────┘

アプリケーションのデプロイ

以下のコマンドでアプリケーションをデプロイします。

npm run deploy

デプロイ後、ブラウザで公開URLを開き、データが正しく表示されていれば成功です。

参考

Discussion