Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 14 additions & 15 deletions proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,13 @@ import { getToken } from "next-auth/jwt";
import { guestRegex, isDevelopmentEnvironment } from "./lib/constants";

export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const { pathname, origin } = request.nextUrl;

if (pathname.startsWith("/ping")) {
return new Response("pong", { status: 200 });
}

if (pathname.startsWith("/api/auth")) {
return NextResponse.next();
}
// Quick responses for simple paths
if (pathname.startsWith("/ping")) return new Response("pong", { status: 200 });
if (pathname.startsWith("/api/auth")) return NextResponse.next();

// Get token once
const token = await getToken({
req: request,
secret: process.env.AUTH_SECRET,
Expand All @@ -21,18 +18,21 @@ export async function proxy(request: NextRequest) {

const base = process.env.NEXT_PUBLIC_BASE_PATH ?? "";

if (!token) {
const redirectUrl = encodeURIComponent(new URL(request.url).pathname);
// Precompute redirect URL once
const redirectUrl = encodeURIComponent(pathname);
Comment on lines +21 to +22
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Precompute redirect URL once
const redirectUrl = encodeURIComponent(pathname);
// Precompute redirect URL once (prepend base because nextUrl.pathname strips basePath)
const redirectUrl = encodeURIComponent(`${base}${pathname}`);

Guest sign-in redirects to wrong path when basePath is configured because request.nextUrl.pathname strips the basePath from the redirect URL.

Fix on Vercel


// Guest redirect if not authenticated
if (!token) {
return NextResponse.redirect(
new URL(`${base}/api/auth/guest?redirectUrl=${redirectUrl}`, request.url)
new URL(`${base}/api/auth/guest?redirectUrl=${redirectUrl}`, origin)
);
}

const isGuest = guestRegex.test(token?.email ?? "");
const isGuest = guestRegex.test(token.email ?? "");

if (token && !isGuest && ["/login", "/register"].includes(pathname)) {
return NextResponse.redirect(new URL(`${base}/`, request.url));
// Authenticated users shouldn't access login/register
if (!isGuest && (pathname === "/login" || pathname === "/register")) {
return NextResponse.redirect(new URL(`${base}/`, origin));
}

return NextResponse.next();
Expand All @@ -45,7 +45,6 @@ export const config = {
"/api/:path*",
"/login",
"/register",

"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};