From 2b5336b9863f86dee82d7300ca2df0d65105041c Mon Sep 17 00:00:00 2001 From: Claudio Wunder Date: Thu, 30 Nov 2023 23:25:25 +0100 Subject: [PATCH] meta: reduce middleware invocations by only running on / --- middleware.ts | 15 ++++++++++----- next.dynamic.mjs | 20 +++++++++++++------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/middleware.ts b/middleware.ts index 45a5154f5af25..95183c635d1c8 100644 --- a/middleware.ts +++ b/middleware.ts @@ -8,10 +8,15 @@ export default createMiddleware({ // Used when no locale matches defaultLocale: defaultLocale.code, + + // Always use a Locale as a prefix for routing + localePrefix: 'always', + + // We already have our own way of providing alternate links + // generated on `next.dynamic.mjs` + alternateLinks: false, }); -export const config = { - // Note.: This needs to be updated when activating more locales - // Format: '/(locale1|locale2|locale3|...)/:path*' - matcher: ['/', '/(en)/:path*'], -}; +// We only want the middleware to run on the `/` route +// to redirect users to their preferred locale +export const config = { matcher: ['/'] }; diff --git a/next.dynamic.mjs b/next.dynamic.mjs index cee5be95e82cf..5046a7240cafb 100644 --- a/next.dynamic.mjs +++ b/next.dynamic.mjs @@ -218,16 +218,22 @@ const getDynamicRouter = async () => { : siteConfig.title; pageMetadata.twitter.title = pageMetadata.title; - pageMetadata.alternates.canonical = `${baseUrlAndPath}/${locale}/${path}`; - pageMetadata.alternates.languages[ - 'x-default' - ] = `${baseUrlAndPath}/${defaultLocale.code}/${path}`; + const getUrlForPathname = (l, p) => + `${baseUrlAndPath}/${l}${p ? `/${p}` : ''}`; + + pageMetadata.alternates.canonical = getUrlForPathname(locale, path); + + pageMetadata.alternates.languages['x-default'] = getUrlForPathname( + defaultLocale.code, + path + ); availableLocaleCodes.forEach(currentLocale => { - pageMetadata.alternates.languages[ - currentLocale - ] = `${baseUrlAndPath}/${currentLocale}/${path}`; + pageMetadata.alternates.languages[currentLocale] = getUrlForPathname( + currentLocale, + path + ); }); return pageMetadata;