Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use host and proto headers to determine request origin if AUTH_URL is not set #12421

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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}`
}
Loading