react-router v7のCloudflare D1用テンプレートで開発を始めた。ORMはDrizzle。
pnpm run dev
であっという間にローカル環境のDBが構築できるのは便利なのだが、デプロイ周りはちょっとだけ作業が必要なので、ここにまとめておく。
プロジェクトを作る
ディレクトリ名を適当に決めて、Readmeに示されたコマンドを打つ。
npx create-react-router@latest --template remix-run/react-router-templates/cloudflare-d1
対話型UIが起動するので、良い感じに回答する。
Where should we create your new project? → ./my-application
Initialize a new git repository? → Yes
Install dependencies with npm? → Yes
cd my-application
なんか色々生えているのがわかる。(tree --gitignore
した)
.
├── README.md
├── app
│ ├── app.css
│ ├── entry.server.tsx
│ ├── root.tsx
│ ├── routes
│ │ └── home.tsx
│ ├── routes.ts
│ └── welcome
│ ├── logo-dark.svg
│ ├── logo-light.svg
│ └── welcome.tsx
├── database
│ └── schema.ts
├── drizzle
│ ├── 0000_outstanding_trauma.sql
│ └── meta
│ ├── 0000_snapshot.json
│ └── _journal.json
├── drizzle.config.ts
├── load-context.ts
├── package-lock.json
├── package.json
├── public
│ └── favicon.ico
├── react-router.config.ts
├── tsconfig.cloudflare.json
├── tsconfig.json
├── tsconfig.node.json
├── vite.config.ts
├── worker-configuration.d.ts
├── workers
│ └── app.ts
└── wrangler.toml
今回気にするのはwrangler.toml
とdrizzle.ts
だけだ。ここさえ設定すれば動くようにできている。
wranglerの設定
Cloudflare Workersのデプロイを担当するCLIがwranglerだ。
まずwranglerにログインする。アカウントは作っておこう。
npx wrangler login
ここでnpm run deploy
をすると、エラーが出てしまう。どうやら、wrangler.toml
の設定で正しいDBが設定されていないのが原因のようだ。というわけで、対象になるD1インスタンスを作成・設定していく。
npm run deploy
✘ [ERROR] You must use a real database in the database_id configuration. You can find your databases using 'wrangler d1 list', or read how to develop locally with D1 here: https://developers.cloudflare.com/d1/configuration/local-development
DBを作る
以下のコマンドでDBを作成する。これを控えておいて、wrangler.toml
を書き換える。DB名はうまいこと決めよう。
npx wrangler d1 create my-application-db
すると↓みたいな出力が出てくる。このdatabase_idを控えておく。
[[d1_databases]]
binding = "DB"
database_name = "my-application-db"
database_id = "****-****-****-****"
これをwrangler.toml
に書き込んでおく。これでwrangler側の設定は完了だ。
[[d1_databases]]
binding = "DB"
- database_name = "your-database-name"
+ database_name = "my-application-db"
- database_id = "your-database-id"
+ database_id = "****-****-****-****"
migrations_dir = "drizzle"
マイグレーション
ORMのDrizzleはdatabase/schema.ts
でスキーマを管理している。
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
export const guestBook = sqliteTable("guestBook", {
id: integer().primaryKey({ autoIncrement: true }),
name: text().notNull(),
email: text().notNull().unique(),
});
まだこのスキーマがDBのテーブル構造に反映されていないので、このままデプロイするとエラーが出てしまう。
マイグレーションしたいが、その前にDrizzleにCloudflareの認証情報を覚えさせてやる必要がある。(愚直にやると↓のエラーが出る)
Error Please provide required params for D1 HTTP driver:
[x] accountId: undefined
[✓] databaseId: 'your-database-id'
[x] token: undefined
3つの認証情報が必要らしい。
database-id
は
accountId
とtoken
の入手方法はDrizzleのドキュメントに丁寧に書かれていた。
- accountId
: サイドバーの「Workers」→「Workers&Pages」に遷移して、右側の「アカウント」欄からコピー
- token
: アカウントの下にある「API トークンの管理」→「トークンを作成する」→「カスタムトークン」で作成画面へ。識別しやすい名前をつけ、「権限」を「アカウント」「D1」「編集」に設定。あとは適当でも大丈夫(後から編集できる)。
これらは環境変数として渡すので、.env
ファイルを作成する。tokenを扱うので、.env
を忘れずにgitignoreしよう!
CLOUDFLARE_ACCOUNT_ID=(アカウントID)
CLOUDFLARE_TOKEN=(さっき発行したtoken)
databaseId
はwrangler.toml
に書いたのと同じものをdrizzle.config.ts
に書き込んでおく。
dbCredentials: {
- databaseId: "your-database-id",
+ databaseId: "****-****-****-****",
accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
token: process.env.CLOUDFLARE_TOKEN!,
},
これでOK。あとはmigrationしよう!
npm run db:migrate-production
$ npm run db:migrate-production
> db:migrate-production
> dotenv -- drizzle-kit migrate
No config path provided, using default 'drizzle.config.ts'
Reading config file '/Users/...'
ついでにlocal環境のmigrationもやっておく。
npm run db:migrate
なんか聞かれるのでy
を押す。
これでnpm run dev
からlocal環境が立ち上がるようになった。
デプロイ
最後にアプリケーションをデプロイする。
npm run deploy
Deployed my-worker triggers (0.43 sec)
https://my-worker.***.workers.dev
はい完了!実際にコマンドラインに表示されたURLを見にいくと、動く形でアプリケーションが動作しているのがわかる。DBへの接続もできる。便利〜。

おわり
めちゃくちゃ簡単にDB + アプリケーションが生えた。
簡単さと安価さとパフォーマンスを全て兼ね備えた良い感じの構成なので、ぜひ触ってみよう。