🐛 Fix infinite loop when trying to migrate legacy cookie (#1561)

This commit is contained in:
Luke Vella 2025-02-13 10:14:03 +07:00 committed by GitHub
parent cb27ae9ea7
commit ff4a1d16cb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 260 additions and 139 deletions

View file

@ -3,44 +3,41 @@ import { withPostHog } from "@rallly/posthog/next/middleware";
import { NextResponse } from "next/server";
import { getLocaleFromHeader } from "@/app/guest";
import { withAuthMigration } from "@/auth/legacy/next-auth-cookie-migration";
import { withAuth } from "@/auth/middleware";
import { withAuth } from "@/auth/edge";
const supportedLocales = Object.keys(languages);
export const middleware = withAuthMigration(
withAuth(async (req) => {
const { nextUrl } = req;
const newUrl = nextUrl.clone();
export const middleware = withAuth(async (req) => {
const { nextUrl } = req;
const newUrl = nextUrl.clone();
const isLoggedIn = req.auth?.user?.email;
const isLoggedIn = req.auth?.user?.email;
// if the user is already logged in, don't let them access the login page
if (/^\/(login)/.test(newUrl.pathname) && isLoggedIn) {
newUrl.pathname = "/";
return NextResponse.redirect(newUrl);
}
// if the user is already logged in, don't let them access the login page
if (/^\/(login)/.test(newUrl.pathname) && isLoggedIn) {
newUrl.pathname = "/";
return NextResponse.redirect(newUrl);
}
// Check if locale is specified in cookie
let locale = req.auth?.user?.locale;
if (locale && supportedLocales.includes(locale)) {
newUrl.pathname = `/${locale}${newUrl.pathname}`;
} else {
// Check if locale is specified in header
locale = await getLocaleFromHeader(req);
newUrl.pathname = `/${locale}${newUrl.pathname}`;
}
// Check if locale is specified in cookie
let locale = req.auth?.user?.locale;
if (locale && supportedLocales.includes(locale)) {
newUrl.pathname = `/${locale}${newUrl.pathname}`;
} else {
// Check if locale is specified in header
locale = await getLocaleFromHeader(req);
newUrl.pathname = `/${locale}${newUrl.pathname}`;
}
const res = NextResponse.rewrite(newUrl);
res.headers.set("x-pathname", newUrl.pathname);
const res = NextResponse.rewrite(newUrl);
res.headers.set("x-pathname", newUrl.pathname);
if (req.auth?.user?.id) {
await withPostHog(res, { distinctID: req.auth.user.id });
}
if (req.auth?.user?.id) {
await withPostHog(res, { distinctID: req.auth.user.id });
}
return res;
}),
);
return res;
});
export const config = {
matcher: ["/((?!api|_next/static|_next/image|static|.*\\.).*)"],