5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

<cicd> Next.js13 を Cloudflare pages に GitHub Actions から Deploy する

Last updated at Posted at 2023-09-03

最近はとりあえず Cloudflare Pages へデプロイすることが多くなってきました。

Cloudflare Pages は素晴らしいサービスで remote repository への push を自動で検知してデプロイしてくれますよね。
ただ、テストを挟みたい時があるかと思います。

そこで今回は GitHub Actions で一通り テストが実行されてから deploy するような workflow を書いてみました。

環境

  • Next.js 13 (app router)
  • cloudflare pages(edge)
  • node 18
  • pnpm 8

流れ

Next.js 13 のプロジェクトを作っている。

  1. Cloudflare と GitHub を紐づける
  2. GitHub Actions から叩くための Cloudlfare access token を発行する
  3. Workflow を作成

1. Cloudflare と GitHub を紐づける

Cloudflare 用の package を入れておく。

pnpm install --save-dev @cloudflare/next-on-pages

runtime を node から edge 変更

layout.tsx
export const runtime = 'edge';
...

Cloudflare と紐づける

ダッシュボードからアカウントに入る。
Pages を GitHub と紐づけておく。
deployの設定がありますが、デフォルトでok

ビルド コマンド: npx @cloudflare/next-on-pages@1
ビルド出力ディレクトリ: .vercel/output/static
ルート ディレクトリ: /

自動デプロイされてしまうので設定を無効にする

スクリーンショット 2023-09-03 15.00.57.png

2. GitHub Actions から叩くための Cloudlfare access token を発行する

こちらのリンクから token を発行します。

カスタムトークンを選択

スクリーンショット 2023-09-03 15.06.14.png

permissions を account / cloudflare pages / edit で作成

他は特に指定しなくて ok。
token が表示されるのでコピーしておく。

参考

3. Workflow を作成

完成系。

  • 自分は pnpm を使っているので pnpm 用の設定を加えています。
  • <project name> は任意の project 名を入れる

大枠は build と deploy の部分を押さえておけば後は自由。

- name: Build
        run: npx @cloudflare/next-on-pages@1
- name: Publish to Cloudflare Pages
        id: cloudflare_pages_deploy
        uses: cloudflare/pages-action@1
        with:
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          projectName: <project name>
          directory: .vercel/output/static
          gitHubToken: ${{ secrets.GITHUB_TOKEN }}

api token を設定

  1. GitHub Actions から叩くための Cloudlfare access token を発行するでコピーしたものを secrets.CLOUDFLARE_API_TOKEN に設定

account id を設定

https://dash.cloudflare.com/ ここから project があるアカウントを選択してください。

その際の url のドメイン以下の文字列が account id となります。
https://dash.cloudflare.com/xxxxxxxxxxxxxx

この xxxx...をsecrets.CLOUDFLARE_ACCOUNT_ID に設定。

完成

こんな感じで push した時に workflow が動きます。
また、1で cloudflare と紐づけているので、bot から PR に通知もきます。

スクリーンショット 2023-09-03 15.32.40.png

余談ですが、今回は一つの workflow に lint と test と depoy を入れていますが、分けた方が良いかもしれないです。ベストプラクティスがわからないので詳しい方教えてください。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?