From 9f1f5b7f95a5c8ae91f88e5ec6597eaecc9b274a Mon Sep 17 00:00:00 2001 From: Luke Vella Date: Thu, 13 Feb 2025 10:26:48 +0700 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Check=20for=20new=20session=20fi?= =?UTF-8?q?rst?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/web/src/auth/edge/with-auth.ts | 13 ++++++++----- .../src/auth/legacy/next-auth-cookie-migration.ts | 11 ++++++++++- apps/web/src/next-auth.ts | 4 ++-- 3 files changed, 20 insertions(+), 8 deletions(-) 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 };