From f57eca19e5d774dc91b486ef5a7ebf8aff87b291 Mon Sep 17 00:00:00 2001 From: Yosuke Furukawa Date: Thu, 18 Apr 2024 16:31:44 +0900 Subject: [PATCH] fix: redirect to default locale page when locale is not supported (#6628) --- app/[locale]/[[...path]]/page.tsx | 17 ++++++++++++++--- next.locales.mjs | 4 ++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/app/[locale]/[[...path]]/page.tsx b/app/[locale]/[[...path]]/page.tsx index 9ac77076d07c7..14aff4e2d41b4 100644 --- a/app/[locale]/[[...path]]/page.tsx +++ b/app/[locale]/[[...path]]/page.tsx @@ -1,5 +1,5 @@ import { setContext, setTags } from '@sentry/nextjs'; -import { notFound } from 'next/navigation'; +import { notFound, redirect } from 'next/navigation'; import { unstable_setRequestLocale } from 'next-intl/server'; import type { FC } from 'react'; @@ -9,7 +9,11 @@ import WithLayout from '@/components/withLayout'; import { ENABLE_STATIC_EXPORT, VERCEL_REVALIDATE } from '@/next.constants.mjs'; import { PAGE_VIEWPORT, DYNAMIC_ROUTES } from '@/next.dynamic.constants.mjs'; import { dynamicRouter } from '@/next.dynamic.mjs'; -import { availableLocaleCodes, defaultLocale } from '@/next.locales.mjs'; +import { + allLocaleCodes, + availableLocaleCodes, + defaultLocale, +} from '@/next.locales.mjs'; import { MatterProvider } from '@/providers/matterProvider'; type DynamicStaticPaths = { path: Array; locale: string }; @@ -67,7 +71,14 @@ const getPage: FC = async ({ params }) => { // Forces the current locale to be the Default Locale unstable_setRequestLocale(defaultLocale.code); - return notFound(); + if (!allLocaleCodes.includes(locale)) { + // when the locale is not listed in the locales, return NotFound + return notFound(); + } + + // Redirect to the default locale path + const pathname = dynamicRouter.getPathname(path); + return redirect(`/${defaultLocale.code}/${pathname}`); } // Configures the current Locale to be the given Locale of the Request diff --git a/next.locales.mjs b/next.locales.mjs index a851101466aa6..4805361a7424b 100644 --- a/next.locales.mjs +++ b/next.locales.mjs @@ -20,7 +20,11 @@ const availableLocalesMap = Object.fromEntries( localeConfig.map(locale => [locale.code, locale]) ); +// Creates all supported locales +const allLocaleCodes = localeConfig.map(locale => locale.code); + export { + allLocaleCodes, availableLocales, availableLocaleCodes, availableLocalesMap,