From fea17ef6e561daf7db8fd5ebfcdf5121430ba906 Mon Sep 17 00:00:00 2001 From: Ben Fichter Date: Wed, 25 Dec 2024 17:23:38 -0500 Subject: [PATCH] Use host and proto headers to determine request origin if AUTH_URL is not set --- packages/next-auth/src/lib/env.ts | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/packages/next-auth/src/lib/env.ts b/packages/next-auth/src/lib/env.ts index 27615af273..29ea4a01b8 100644 --- a/packages/next-auth/src/lib/env.ts +++ b/packages/next-auth/src/lib/env.ts @@ -3,9 +3,12 @@ import { NextRequest } from "next/server" import type { NextAuthConfig } from "./index.js" import { setEnvDefaults as coreSetEnvDefaults } from "@auth/core" -/** If `NEXTAUTH_URL` or `AUTH_URL` is defined, override the request's URL. */ +/** If `NEXTAUTH_URL` or `AUTH_URL` is defined or host headers are set, + * override the request's URL. + */ export function reqWithEnvURL(req: NextRequest): NextRequest { - const url = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL + const url = + process.env.AUTH_URL ?? process.env.NEXTAUTH_URL ?? urlFromHeaders(req) if (!url) return req const { origin: envOrigin } = new URL(url) const { href, origin } = req.nextUrl @@ -35,3 +38,19 @@ export function setEnvDefaults(config: NextAuthConfig) { coreSetEnvDefaults(process.env, config, true) } } + +function urlFromHeaders(req: NextRequest): string | null { + const detectedHost = + req.headers.get("x-forwarded-host") ?? req.headers.get("host") + + if (!detectedHost) { + return null + } + + const detectedProtocol = + req.headers.get("x-forwarded-proto") ?? req.protocol ?? "https" + const _protocol = detectedProtocol.endsWith(":") + ? detectedProtocol + : detectedProtocol + ":" + return `${_protocol}//${detectedHost}` +}