Closed2

Next.js(Edge runtime)でNextAuth.jsを動かす

mr_ozinmr_ozin

2024-01-03

Vercelではうまくいったが、Cloudflare Pagesだと上手くいかないので一旦クローズ。


執筆時点の情報です。現在開発中なので大きな変更が入っているかもしれません。あまり確定していない箇所もあるので間違いがあるかもしれません。

経由

Next.jsをEdge runtimeで動作させた場合、NextAuth.jsって動くんだっけ?と思って調べたら、下記のIssueで動くと報告があった。

https://github.com/nextauthjs/next-auth/discussions/5855#discussioncomment-4564329

動かすにはbeta版で導入する必要がある。Client/Server Componentsでどうやって動かすのかの対応表は下記に書いてある。

https://authjs.dev/guides/upgrade-to-v5

動かす(Vercel)

が、これだけだと動作するコードがよくわからないので、公式のExampleからforkして、Edge runtimeで動くようにして、Vercelにデプロイした。

リポジトリ

https://github.com/ryokryok/next-auth-edge-example

デモ

https://next-auth-edge-example.vercel.app/

やっていることはClient Componentとして動かす以外のルートに下記を追加した程度。

export const runtime = "edge"
mr_ozinmr_ozin

Cloudflare Pagesでは動かない?(@cloudflare/next-on-pages)

2024-01-03 更新

Next.jsをCloudflare Pagesで動作させるためのツールがある。Edge runtimeでの動作を想定したものらしい。

https://developers.cloudflare.com/pages/framework-guides/deploy-a-nextjs-site/

ただ、下記のIssueがある通り、Pages向けのビルドを実行した際にエラーになる。そのためデプロイ出来ない。(NextAuth.jsの組み合わせだと上手くいっていない?原因の切り分けができていません)

https://github.com/cloudflare/next-on-pages/issues/413

2024-01-03時点だと @cloudflare/next-on-pages": "^1.8.3 でビルドはこけなくなったのでデプロイはできた。

https://next-auth-edge-example.pages.dev/

が、ログインしようとすると、エラーが出て進めない。

ログとしては下記が出ていた。

POST https://next-auth-edge-example.pages.dev/ - Ok @ 2024/1/3 16:58:48
  (error) [auth][error] UntrustedHost: Host must be trusted. URL was: https://next-auth-edge-example.pages.dev/ .Read more at https://errors.authjs.dev#untrustedhost
  (error)     at ea (__next-on-pages-dist__/functions/middleware.func.js:9:31246)
    at er (__next-on-pages-dist__/functions/middleware.func.js:353:51171)
GET https://next-auth-edge-example.pages.dev/api/auth/signin?callbackUrl=https%3A%2F%2Fnext-auth-edge-example.pages.dev%2F - Ok @ 2024/1/3 16:58:48
  (error) [auth][error] UntrustedHost: Host must be trusted. URL was: https://next-auth-edge-example.pages.dev/api/auth .Read more at https://errors.authjs.dev#untrustedhost
  (error)     at __next-on-pages-dist__/webpack/e9146e72f071480886a0c9d55654047c.js:354:37662
    at Hr (__next-on-pages-dist__/webpack/e9146e72f071480886a0c9d55654047c.js:354:39350)
    at async __next-on-pages-dist__/webpack/619b8906e43c61d2d643fd0d11a3a114.js:10:27780

確認した項目

GitHub 側

Cloudflare Pages側

  • Settings > Environment variablesにて、.env.local と同じになるように設定
  • Settings > Functionsにて、Compatibility flagsの項にてnodejs_compat を指定
このスクラップは2024/01/03にクローズされました