From ae3c7070fdcedbc5ac8c10bc335d17d63cc6c499 Mon Sep 17 00:00:00 2001 From: Roland Broekema Date: Thu, 14 Aug 2025 15:28:40 +0200 Subject: [PATCH] fix(auth): preserve basePath in request URL reconstruction (#13034) Ensure that reqWithEnvURL can correctly restore the API call path when Next.js strips it from incoming requests. Refs: https://github.com/nextauthjs/next-auth/issues/13034 --- packages/next-auth/src/lib/env.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/next-auth/src/lib/env.ts b/packages/next-auth/src/lib/env.ts index 27615af273..4375c1fdcd 100644 --- a/packages/next-auth/src/lib/env.ts +++ b/packages/next-auth/src/lib/env.ts @@ -3,13 +3,21 @@ 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, override the request's URL. + * Reset the basePath onto the url as it checks the full url in nextauth api handlers + * References: + * - Bug in Next.js affecting URL handling: https://github.com/vercel/next.js/issues/62756 + * - Bug in NextAuth causing incorrect action, redirect URL behavior: https://github.com/nextauthjs/next-auth/issues/13034 + */ export function reqWithEnvURL(req: NextRequest): NextRequest { const url = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL + // nextjs basepath not auth config basepath + const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '' if (!url) return req const { origin: envOrigin } = new URL(url) const { href, origin } = req.nextUrl - return new NextRequest(href.replace(origin, envOrigin), req) + return new NextRequest(href.replace(origin, envOrigin + basePath), req) } /**