Skip to content

Commit

Permalink
refactor:  simplyfy logic
Browse files Browse the repository at this point in the history
  • Loading branch information
nicholasio committed Jul 24, 2024
1 parent 3641329 commit 50cedf2
Showing 1 changed file with 8 additions and 16 deletions.
24 changes: 8 additions & 16 deletions packages/next/src/middlewares/appMidleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -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),
Expand Down

0 comments on commit 50cedf2

Please sign in to comment.