From 6e945c49d851afc9698daf0e7eff759825077919 Mon Sep 17 00:00:00 2001 From: hailin Date: Thu, 17 Apr 2025 13:17:01 +0800 Subject: [PATCH] . --- middleware.ts | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/middleware.ts b/middleware.ts index 661d31a..7dbb2ed 100644 --- a/middleware.ts +++ b/middleware.ts @@ -4,28 +4,26 @@ import { NextResponse, type NextRequest } from "next/server" import i18nConfig from "./i18nConfig" export async function middleware(request: NextRequest) { - const { pathname } = request.nextUrl + // ✅ 从 Cookie 中获取语言 + const preferredLang = request.cookies.get("preferred-language")?.value - // ✅ 读取 cookie 中用户偏好的语言 - const preferredLanguage = request.cookies.get('preferred-language')?.value + // ✅ 如果没有语言前缀,且 Cookie 中有语言偏好,则重定向一次 + const pathname = request.nextUrl.pathname + const firstSegment = pathname.split("/")[1] + const hasLocalePrefix = i18nConfig.locales.includes(firstSegment as any) - // ✅ 判断是否需要重定向到带有语言前缀的 URL - const isMissingLocalePrefix = !i18nConfig.locales.some(locale => - pathname.startsWith(`/${locale}/`) || pathname === `/${locale}` - ) - - if (preferredLanguage && isMissingLocalePrefix) { - const url = request.nextUrl.clone() - url.pathname = `/${preferredLanguage}${pathname}` - return NextResponse.redirect(url) + if (!hasLocalePrefix && preferredLang && i18nConfig.locales.includes(preferredLang)) { + const newUrl = new URL(`/${preferredLang}${pathname}`, request.url) + return NextResponse.redirect(newUrl) } - // ✅ 原始的 i18n 路由逻辑(保留) + // 👇 这个要留着,用于 next-i18n-router 自动 locale 路由处理 const i18nResult = i18nRouter(request, i18nConfig) if (i18nResult) return i18nResult try { const { supabase, response } = createClient(request) + const session = await supabase.auth.getSession() const redirectToChat = session && request.nextUrl.pathname === "/" @@ -38,7 +36,9 @@ export async function middleware(request: NextRequest) { .eq("is_home", true) .single() - if (!homeWorkspace) throw new Error(error?.message) + if (!homeWorkspace) { + throw new Error(error?.message) + } return NextResponse.redirect( new URL(`/${homeWorkspace.id}/chat`, request.url) @@ -48,7 +48,9 @@ export async function middleware(request: NextRequest) { return response } catch (e) { return NextResponse.next({ - request: { headers: request.headers } + request: { + headers: request.headers + } }) } }