From 50cedf2054bbe2dc96b0374776dfde1bd68f7dd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?N=C3=ADcholas=20Andr=C3=A9?= Date: Wed, 24 Jul 2024 00:12:57 +0000 Subject: [PATCH] =?UTF-8?q?refactor:=20=C2=A0simplyfy=20logic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/next/src/middlewares/appMidleware.ts | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/packages/next/src/middlewares/appMidleware.ts b/packages/next/src/middlewares/appMidleware.ts index c85ad820d..db0d3ca25 100644 --- a/packages/next/src/middlewares/appMidleware.ts +++ b/packages/next/src/middlewares/appMidleware.ts @@ -72,7 +72,7 @@ export function getAppRouterLocale(request: NextRequest): [string, string] | und return undefined; } - // if there's a locale in the URL and it's a supported locale, use it + // if there's a locale in the URL and it's a supported or valid locale, use it const urlLocale = request.nextUrl.pathname.split('/')[1]; if (supportedLocales.includes(urlLocale) || isValidLocale(urlLocale)) { return [defaultLocale, urlLocale]; @@ -166,24 +166,16 @@ export async function AppMiddleware( ); if (locale && options.appRouter) { + // if we detected a non-default locale, there isn't a supported locale in the URL already + // but the first part of pathname (what is assumed to be a locale) is not a valid locale + // then we should redirect to add the locale + // e.g /about-us -> /en/about-us if ( + locale && locale !== defaultAppRouterLocale && - locale !== firstPathSlice && - supportedLocales.includes(firstPathSlice) + pathnameIsMissingLocale && + !isValidLocale(firstPathSlice) ) { - shouldRedirect = true; - response = NextResponse.redirect( - new URL( - `/${locale}${pathname.startsWith('/') ? '' : '/'}${pathname.replace(`/${firstPathSlice}`, '')}`, - req.url, - ), - ); - } - - // if we detected a locale, there isn't a supported locale in the URL - // but the first part of pathname (what is assumed to be urlLocale) is not a valid locale - // then we should redirect to add the locale - if (locale && pathnameIsMissingLocale && !isValidLocale(firstPathSlice)) { shouldRedirect = true; response = NextResponse.redirect( new URL(`/${locale}${pathname.startsWith('/') ? '' : '/'}${pathname}`, req.url),