Post

Cloudflare Pages へ GitHub Actions で自動デプロイする

React SPA を Cloudflare Pages へ GitHub Actions で自動デプロイする設定方法。

ワークフローファイル

.github/workflows/deploy.yml:

name: Deploy to Cloudflare Pages on: push: branches: [main] paths: - 'react-spa-cloudflare/**' workflow_dispatch: defaults: run: working-directory: react-spa-cloudflare jobs: deploy: runs-on: ubuntu-latest permissions: contents: read deployments: write steps: - uses: actions/checkout@v4 - name: Use Node.js 22 uses: actions/setup-node@v4 with: node-version: '22' cache: 'npm' cache-dependency-path: react-spa-cloudflare/package-lock.json - name: Install dependencies run: npm ci - name: Build run: npm run build - name: Deploy to Cloudflare Pages uses: cloudflare/wrangler-action@v3 with: apiToken: $ accountId: $ command: pages deploy dist --project-name=react-spa-cloudflare workingDirectory: react-spa-cloudflare

必要な Secrets

GitHub Repository → Settings → Secrets → Actions で設定:

Secret 取得方法
CLOUDFLARE_ACCOUNT_ID Cloudflare ダッシュボード右サイドバー
CLOUDFLARE_API_TOKEN Profile → API Tokens → Create Token

API Token の権限

「Create Custom Token」で以下を設定:

  • Permissions: AccountCloudflare PagesEdit
  • Account Resources: 対象アカウントを選択

初回セットアップ (Makefile)

pages-login: npx wrangler login pages-create: npx wrangler pages project create react-spa-cloudflare --production-branch=main deploy: npm run build npx wrangler pages deploy dist --project-name=react-spa-cloudflare
make pages-login # Cloudflare にログイン make pages-create # Pages プロジェクト作成 make deploy # 初回デプロイ

wrangler.toml

Pages 用の設定ファイル。[build] セクションは使用不可。

name = "react-spa-cloudflare" compatibility_date = "2024-01-01" pages_build_output_dir = "dist"

カスタムドメイン

デプロイ後、Cloudflare ダッシュボードで設定:

  1. Workers & Pages → プロジェクト選択
  2. Custom domains → Set up a custom domain
  3. サブドメイン入力 → Activate domain

DNS が Cloudflare にある場合、CNAME は自動追加される。

トラブルシューティング

Authentication error [code: 10000]

API Token の権限不足。Cloudflare Pages:Edit 権限があるか確認。

Configuration file does not support “build”

wrangler.toml から [build] セクションを削除。Pages CLI では非サポート。

This post is licensed under CC BY 4.0 by the author.