From c7f2b832895330874dfdc7d53a1e18c1924d7f20 Mon Sep 17 00:00:00 2001 From: John Munson <19480078+johncmunson@users.noreply.github.com> Date: Thu, 14 Aug 2025 02:40:28 -0500 Subject: [PATCH] Update nextjsMiddlewareRedirect Update nextjsMiddlewareRedirect to handle routes that contain query params --- src/nextjs/server/index.tsx | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/nextjs/server/index.tsx b/src/nextjs/server/index.tsx index 24a1f62..7985946 100644 --- a/src/nextjs/server/index.tsx +++ b/src/nextjs/server/index.tsx @@ -295,7 +295,11 @@ export { createRouteMatcher, RouteMatcherParam } from "./routeMatcher.js"; * a Next.js middleware. * * ```ts + * // Plain redirect * return nextjsMiddlewareRedirect(request, "/login"); + * + * // Redirect with query params + * return nextjsMiddlewareRedirect(request, "/login?next=/app/dashboard"); * ``` */ export function nextjsMiddlewareRedirect( @@ -304,12 +308,27 @@ export function nextjsMiddlewareRedirect( */ request: NextRequest, /** - * The route path to redirect to. + * The route to redirect to. */ - pathname: string, + route: string, ) { const url = request.nextUrl.clone(); - url.pathname = pathname; + + // Parse the incoming route so we can split path & query correctly + // Prepend a dummy origin because URL() requires absolute URLs + const parsed = new URL(route, "http://dummy"); + + // Assign the path + url.pathname = parsed.pathname; + + // Clear any existing search params + url.search = ""; + + // Copy search params from the provided route + parsed.searchParams.forEach((value, key) => { + url.searchParams.set(key, value); + }); + return NextResponse.redirect(url); }