プレビューデプロイ
Cloudflare Pages での PR ごとのプレビューデプロイ
プレビューデプロイの仕組み
main 以外のブランチ名でデプロイすると、Cloudflare Pages は固有の URL を持つプレビューデプロイを作成します:
https://<branch>.<account>-<project>.pages.dev PR ベースのプレビューでは、PR 番号をブランチとして使用します:
npx wrangler@4 pages deploy deploy \
--project-name=my-site \
--branch="pr-${PR_NUMBER}" \
--commit-hash="${GITHUB_SHA}" \
--commit-message="Preview: PR #${PR_NUMBER}"プレビュー URL は次のようになります:
https://pr-42.takazudo-my-site.pages.dev プレビュー URL のパターン
URL のフォーマットは次の通りです:
https://<branch-slug>.<account-slug>-<project-name>.pages.dev 各要素の意味:
<branch-slug>は--branchで指定した値(サニタイズ済み)<account-slug>は Cloudflare アカウントから自動生成される値<project-name>は--project-nameで指定した値
Note
<account-slug> の部分は Cloudflare が自動生成します。正確なサブドメインの形式は Pages ダッシュボードで確認してください。
PR にプレビュー URL をコメントする
actions/github-script を使って、プレビュー URL のコメントを投稿または更新します:
- name: Comment preview URL on PR
uses: actions/github-script@v8
env:
DEPLOY_URL: ${{ steps.cf-deploy.outputs.deploy_url }}
with:
script: |
const deployUrl = process.env.DEPLOY_URL;
const prNumber = context.issue.number;
const marker = '<!-- cf-preview-pr -->';
const body = [
marker,
`## Cloudflare Pages Preview`,
'',
`Preview deployment is ready.`,
'',
`| | URL |`,
`|---|---|`,
`| Preview | ${deployUrl} |`,
'',
`Built from commit: \`${context.sha.substring(0, 7)}\``,
].join('\n');
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
});
const existing = comments.find(c => c.body.includes(marker));
if (existing) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
body,
});
}HTML コメントマーカー(<!-- cf-preview-pr -->)により、後続のデプロイでは新しいコメントを作成する代わりに既存のコメントが更新されます。
必要な権限
ワークフローには pull-requests: write 権限が必要です:
permissions:
contents: read
pull-requests: writeフォークからの PR ではプレビューが動かない
GitHub は、フォークからの pull request によってトリガーされたワークフローにリポジトリのシークレットを渡さない。プレビューデプロイのワークフローが pull_request イベントで動いていて、その PR がフォークから来ている場合、CLOUDFLARE_API_TOKEN と CLOUDFLARE_ACCOUNT_ID は空文字列になり、デプロイステップは認証エラーで失敗する。
Note
これはこの構成のバグではなく、GitHub Actions の想定通りの挙動だ。プレビューデプロイが動くのは、このリポジトリに直接プッシュされたブランチ(同一リポジトリ内の PR)のみ。外部コントリビューターによるフォーク PR にはプレビュー URL が付かない。これを避けるには pull_request_target(リポジトリのシークレットを持ったままフォーク側のコードを実行するため、単なる回避策ではなくセキュリティ上の判断として扱うこと)に切り替えるか、ビルドはフォーク側で行い承認後にデプロイする、という二段階のワークフローに分割する必要がある。