Closed8

[Next.js & Auth.js & Cloud Run] "UntrustedHost: Host must be trusted" エラー

nbstshnbstsh

Cloud Run に deploy した Next.js App で Auth.js で実装した認証機能利用しようとしたところ以下エラー発生。解決までの道のりをメモする。

Host must be trusted. URL was: https://my-app-service-cpgjiadqyq-an.a.run.app/api/auth/session. Read more at https://errors.authjs.dev#untrustedhost
nbstshnbstsh

UntrustedHost error

https://authjs.dev/reference/core/errors#untrustedhost

Thrown when the trustHost option was not set to true.

Auth.js requires the trustHost option to be set to true since it’s relying on the request headers’ host value.

nbstshnbstsh

trustHost: true にすれば解決しそうだが、trustHost: true にすると何が起こるのかよくわからん...

nbstshnbstsh

AUTH_TRUST_HOST env var

https://authjs.dev/getting-started/deployment#auth_trust_host

When deploying your application behind a reverse proxy, you’ll need to set AUTH_TRUST_HOST equal to true. This tells Auth.js to trust the X-Forwarded-Host header from the reverse proxy. Auth.js will automatically infer this to be true if we detect the environment variable indicating that your application is running on one of the supported hosting providers. Currently VERCEL and CF_PAGES (Cloudflare Pages) are supported.

"trust host" ってのは、reverse proxy からの X-Forwarded-Host header の値を "trust" しますよ、ってことか

trustHost option と AUTH_TRUST_HOST env var どっち使えばいいんだ...?

nbstshnbstsh

Docker environment

https://authjs.dev/getting-started/deployment#docker

In a Docker environment, make sure to set either trustHost: true in your Auth.js configuration or the AUTH_TRUST_HOST environment variable to true.

答え見つけた。Docker 使った self-hosted な環境では、"trust host" を有効化させてね、って書いてあった。

trustHost option と AUTH_TRUST_HOST env var どっち使えばいいんだ...?

trustHost option でも AUTH_TRUST_HOST env var でもどっちでもいいっぽい。

nbstshnbstsh

解決

NextAuth config trustHost を true にしてあげればOK

src/auth.ts
export const { handlers, signIn, signOut, auth } = NextAuth({
+  trustHost: true,
  //...
});
このスクラップは2024/05/11にクローズされました