This commit is contained in:
hailin 2025-04-17 13:17:01 +08:00
parent 6fbfbf53b8
commit 6e945c49d8
1 changed files with 17 additions and 15 deletions

View File

@ -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
}
})
}
}