fix: build login redirects from public host behind Caddy proxy

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-22 00:55:21 -05:00
parent 117c981275
commit ee1250c724

View File

@ -11,6 +11,25 @@ const PUBLIC_ASSETS = [
"/apple-touch-icon.png",
];
/** Public site origin when Next.js runs behind Caddy on localhost:4015. */
function publicOrigin(request: NextRequest): string {
const fromEnv = String(process.env.DY_PUBLIC_BASE_URL || process.env.NEXT_PUBLIC_SITE_URL || "").trim();
if (fromEnv) return fromEnv.replace(/\/$/, "");
const xfHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || "";
const xfProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || "https";
if (xfHost && !xfHost.includes("localhost") && !xfHost.startsWith("127.")) {
return `${xfProto}://${xfHost}`;
}
const host = request.headers.get("host")?.trim() || "";
if (host && !host.includes("localhost") && !host.startsWith("127.")) {
return `${xfProto}://${host}`;
}
return request.nextUrl.origin;
}
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (
@ -24,20 +43,20 @@ export function middleware(request: NextRequest) {
const session = request.cookies.get("dy_session")?.value;
const isLogin = PUBLIC.some((p) => pathname === p || pathname.startsWith(`${p}/`));
const origin = publicOrigin(request);
if (!session && !isLogin) {
// Relative redirect: behind Caddy, request.nextUrl host is localhost:4015.
const next = encodeURIComponent(pathname);
return NextResponse.redirect(`/login?next=${next}`);
const loginUrl = new URL("/login", origin);
loginUrl.searchParams.set("next", pathname);
return NextResponse.redirect(loginUrl);
}
if (session && isLogin) {
return NextResponse.redirect("/");
return NextResponse.redirect(new URL("/", origin));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image).*)"],
};