Skip to content

Commit

Permalink
Use host and proto headers to determine request origin if AUTH_URL is…
Browse files Browse the repository at this point in the history
… not set
  • Loading branch information
bfichter committed Dec 25, 2024
1 parent faf4c9f commit fea17ef
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions packages/next-auth/src/lib/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}`
}

0 comments on commit fea17ef

Please sign in to comment.