feat: support reverse proxied base URLs (#1788)

This commit is contained in:
Bereket Engida
2025-03-12 15:35:13 +03:00
committed by GitHub
parent baef00f5d7
commit 36a7d87aa7
2 changed files with 29 additions and 8 deletions
+11 -7
View File
@@ -9,9 +9,10 @@ import type {
AuthContext,
} from "./types";
import type { PrettifyDeep, Expand } from "./types/helper";
import { getBaseURL } from "./utils/url";
import { getBaseURL, getOrigin } from "./utils/url";
import type { FilterActions, InferAPI } from "./types";
import { BASE_ERROR_CODES } from "./error/codes";
import { BetterAuthError } from "./error";
export type WithJsDoc<T, D> = Expand<T & D>;
@@ -31,12 +32,16 @@ export const betterAuth = <O extends BetterAuthOptions>(options: O) => {
handler: async (request: Request) => {
const ctx = await authContext;
const basePath = ctx.options.basePath || "/api/auth";
const url = new URL(request.url);
if (!ctx.options.baseURL) {
const baseURL =
getBaseURL(undefined, basePath) || `${url.origin}${basePath}`;
ctx.options.baseURL = baseURL;
ctx.baseURL = baseURL;
const baseURL = getBaseURL(undefined, basePath, request);
if (baseURL) {
ctx.baseURL = baseURL;
ctx.options.baseURL = getOrigin(ctx.baseURL) || undefined;
} else {
throw new BetterAuthError(
"Could not get base URL from request. Please provide a valid base URL.",
);
}
}
ctx.trustedOrigins = [
...(options.trustedOrigins
@@ -45,7 +50,6 @@ export const betterAuth = <O extends BetterAuthOptions>(options: O) => {
: await options.trustedOrigins(request)
: []),
ctx.options.baseURL!,
url.origin,
];
const { handler } = router(ctx, options);
return handler(request);
+18 -1
View File
@@ -21,10 +21,11 @@ function withPath(url: string, path = "/api/auth") {
return `${url.replace(/\/+$/, "")}${path}`;
}
export function getBaseURL(url?: string, path?: string) {
export function getBaseURL(url?: string, path?: string, request?: Request) {
if (url) {
return withPath(url, path);
}
const fromEnv =
env.BETTER_AUTH_URL ||
env.NEXT_PUBLIC_BETTER_AUTH_URL ||
@@ -37,6 +38,22 @@ export function getBaseURL(url?: string, path?: string) {
return withPath(fromEnv, path);
}
const fromRequest = request?.headers.get("x-forwarded-host");
const fromRequestProto = request?.headers.get("x-forwarded-proto");
if (fromRequest && fromRequestProto) {
return withPath(`${fromRequestProto}://${fromRequest}`, path);
}
if (request) {
const url = getOrigin(request.url);
if (!url) {
throw new BetterAuthError(
"Could not get origin from request. Please provide a valid base URL.",
);
}
return withPath(url, path);
}
if (typeof window !== "undefined" && window.location) {
return withPath(window.location.origin, path);
}