[Next.js & Auth.js & Cloud Run] "UntrustedHost: Host must be trusted" エラー
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
Read more at https://errors.authjs.dev#untrustedhost
とあるので読む
UntrustedHost error
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.
trustHost
Auth.js relies on the incoming request’s host header to function correctly. For this reason this property needs to be set to true.
Make sure that your deployment platform sets the host header safely.
trustHost: true にすれば解決しそうだが、trustHost: true にすると何が起こるのかよくわからん...
AUTH_TRUST_HOST env var
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 どっち使えばいいんだ...?
Docker environment
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" を有効化させてね、って書いてあった。
trustHostoption とAUTH_TRUST_HOSTenv var どっち使えばいいんだ...?
trustHost option でも AUTH_TRUST_HOST env var でもどっちでもいいっぽい。
解決
NextAuth config trustHost を true にしてあげればOK
export const { handlers, signIn, signOut, auth } = NextAuth({
+ trustHost: true,
//...
});