diff --git a/middleware.ts b/middleware.ts index 55278f0..66bdd7c 100644 --- a/middleware.ts +++ b/middleware.ts @@ -52,7 +52,11 @@ export async function middleware(request: NextRequest) { } if (session && (pathname === "/" || pathname === "/login")) { - return NextResponse.redirect(new URL(getDefaultPathForRole(session.role), baseUrl)); + const requested = request.nextUrl.searchParams.get("next"); + const hasSafeNext = typeof requested === "string" && requested.startsWith("/") && !requested.startsWith("//"); + const nextPath = hasSafeNext ? requested : null; + const destination = nextPath && canAccessPath(session.role, nextPath) ? nextPath : getDefaultPathForRole(session.role); + return NextResponse.redirect(new URL(destination, baseUrl)); } if (session && !isPublicPath(pathname) && !canAccessPath(session.role, pathname)) {