From ee1250c72445302b2d94fd3ae893d6b72217976f Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 22 Aug 2026 00:55:21 -0500 Subject: [PATCH] fix: build login redirects from public host behind Caddy proxy Co-authored-by: Cursor --- frontend/src/middleware.ts | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/frontend/src/middleware.ts b/frontend/src/middleware.ts index 70d73c6..dea43e9 100644 --- a/frontend/src/middleware.ts +++ b/frontend/src/middleware.ts @@ -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).*)"], };