diff --git a/src/middleware.ts b/src/middleware.ts index 68635e9..2052b9e 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,7 +1,12 @@ import { betterFetch } from '@better-fetch/fetch'; import createMiddleware from 'next-intl/middleware'; import { type NextRequest, NextResponse } from 'next/server'; -import { LOCALES, routing } from './i18n/routing'; +import { + DEFAULT_LOCALE, + LOCALES, + LOCALE_COOKIE_NAME, + routing, +} from './i18n/routing'; import type { Session } from './lib/auth-types'; import { getBaseUrl } from './lib/urls/urls'; import { @@ -23,9 +28,31 @@ const intlMiddleware = createMiddleware(routing); * to handle redirection. To avoid blocking requests by making API or database calls. */ export default async function middleware(req: NextRequest) { - const { nextUrl, headers } = req; + const { nextUrl } = req; console.log('>> middleware start, pathname', nextUrl.pathname); + // Handle internal docs link redirection for internationalization + // Check if this is a docs page without locale prefix + if (nextUrl.pathname.startsWith('/docs/')) { + // Get the user's preferred locale from cookie + const localeCookie = req.cookies.get(LOCALE_COOKIE_NAME); + const preferredLocale = localeCookie?.value; + + // If user has a non-default locale preference, redirect to localized version + if ( + preferredLocale && + preferredLocale !== DEFAULT_LOCALE && + LOCALES.includes(preferredLocale) + ) { + const localizedPath = `/${preferredLocale}${nextUrl.pathname}${nextUrl.search}${nextUrl.hash}`; + console.log( + '<< middleware end, redirecting docs link to preferred locale:', + localizedPath + ); + return NextResponse.redirect(new URL(localizedPath, nextUrl)); + } + } + // do not use getSession() here, it will cause error related to edge runtime // const session = await getSession(); const { data: session } = await betterFetch(