diff --git a/apps/web/src/auth/edge/with-auth.ts b/apps/web/src/auth/edge/with-auth.ts index 226c7f5d1..2ca2a771f 100644 --- a/apps/web/src/auth/edge/with-auth.ts +++ b/apps/web/src/auth/edge/with-auth.ts @@ -15,19 +15,22 @@ export const withAuth = ( middleware: (request: NextAuthRequest) => Promise, ) => { return async (request: NextAuthRequest) => { - let legacySession: Session | null = null; + let session: Session | null = null; try { - legacySession = await getLegacySession(); + session = await auth(); } catch (e) { console.error(e); } - let session = legacySession; + let isLegacySession = false; if (!session) { try { - session = await auth(); + session = await getLegacySession(); + if (session) { + isLegacySession = true; + } } catch (e) { console.error(e); } @@ -50,7 +53,7 @@ export const withAuth = ( const middlewareRes = await middleware(request); - if (legacySession) { + if (isLegacySession) { try { await migrateLegacyJWT(middlewareRes); } catch (e) { diff --git a/apps/web/src/auth/legacy/next-auth-cookie-migration.ts b/apps/web/src/auth/legacy/next-auth-cookie-migration.ts index 0faac5613..8995c2357 100644 --- a/apps/web/src/auth/legacy/next-auth-cookie-migration.ts +++ b/apps/web/src/auth/legacy/next-auth-cookie-migration.ts @@ -58,6 +58,7 @@ export async function migrateLegacyJWT(res: NextResponse) { salt: newCookieName, }); + // Set new session cookie res.cookies.set(newCookieName, newJWT, { httpOnly: true, secure: isSecureCookie, @@ -65,6 +66,14 @@ export async function migrateLegacyJWT(res: NextResponse) { sameSite: "lax", path: "/", }); - res.cookies.delete(oldCookieName); + + // Delete the old cookie + res.cookies.set(oldCookieName, "", { + httpOnly: true, + secure: isSecureCookie, + expires: new Date(0), + sameSite: "lax", + path: "/", + }); } } diff --git a/apps/web/src/next-auth.ts b/apps/web/src/next-auth.ts index 9f34fa13b..60b17daf4 100644 --- a/apps/web/src/next-auth.ts +++ b/apps/web/src/next-auth.ts @@ -177,12 +177,12 @@ const { }); const auth = async () => { - const session = await getLegacySession(); + const session = await originalAuth(); if (session) { return session; } - return originalAuth(); + return getLegacySession(); }; export { auth, handlers, signIn, signOut };