From d1194400b2fe7b50ba8c34b162effcf8e3087f35 Mon Sep 17 00:00:00 2001 From: Luke Vella Date: Thu, 12 Sep 2024 09:28:52 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Include=20locale=20when=20creati?= =?UTF-8?q?ng=20guest=20user?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/web/src/app/guest.ts | 11 ++++++++++- apps/web/src/middleware.ts | 12 +++++++----- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/apps/web/src/app/guest.ts b/apps/web/src/app/guest.ts index 55096a8f4..20d245c3a 100644 --- a/apps/web/src/app/guest.ts +++ b/apps/web/src/app/guest.ts @@ -42,7 +42,15 @@ export async function resetUser(res: NextResponse) { await setCookie(res, jwt); } -export async function initGuest(req: NextRequest, res: NextResponse) { +export async function initGuest( + req: NextRequest, + res: NextResponse, + { + locale, + }: { + locale: string; + }, +) { const { name } = getCookieSettings(); if (req.cookies.has(name)) { @@ -53,6 +61,7 @@ export async function initGuest(req: NextRequest, res: NextResponse) { const jwt: JWT = { sub: `user-${randomid()}`, email: null, + locale, }; await setCookie(res, jwt); diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts index 63adc62c9..9a3425677 100644 --- a/apps/web/src/middleware.ts +++ b/apps/web/src/middleware.ts @@ -23,23 +23,25 @@ export const middleware = withAuth( } // Check if locale is specified in cookie - const preferredLocale = req.nextauth.token?.locale; - if (preferredLocale && supportedLocales.includes(preferredLocale)) { - newUrl.pathname = `/${preferredLocale}${newUrl.pathname}`; + let locale = req.nextauth.token?.locale; + if (locale && supportedLocales.includes(locale)) { + newUrl.pathname = `/${locale}${newUrl.pathname}`; } else { // Check if locale is specified in header const acceptLanguageHeader = headers.get("accept-language"); const localeFromHeader = acceptLanguageHeader ? languageParser.pick(supportedLocales, acceptLanguageHeader) : null; - const locale = localeFromHeader ?? "en"; + locale = localeFromHeader ?? "en"; newUrl.pathname = `/${locale}${newUrl.pathname}`; } const res = NextResponse.rewrite(newUrl); - await initGuest(req, res); + await initGuest(req, res, { + locale, + }); return res; },