61 lines
1.8 KiB
TypeScript
61 lines
1.8 KiB
TypeScript
import { createClient } from "@/lib/supabase/middleware"
|
|
import { i18nRouter } from "next-i18n-router"
|
|
import { NextResponse, type NextRequest } from "next/server"
|
|
import i18nConfig from "./i18nConfig"
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
// ✅ 从 Cookie 中获取语言
|
|
const preferredLang = 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)
|
|
|
|
if (!hasLocalePrefix && preferredLang && i18nConfig.locales.includes(preferredLang)) {
|
|
const newUrl = new URL(`/${preferredLang}${pathname}`, request.url)
|
|
return NextResponse.redirect(newUrl)
|
|
}
|
|
|
|
// 👇 这个要留着,用于 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 === "/"
|
|
|
|
if (redirectToChat) {
|
|
const { data: homeWorkspace, error } = await supabase
|
|
.from("workspaces")
|
|
.select("*")
|
|
.eq("user_id", session.data.session?.user.id)
|
|
.eq("is_home", true)
|
|
.single()
|
|
|
|
if (!homeWorkspace) {
|
|
throw new Error(error?.message)
|
|
}
|
|
|
|
return NextResponse.redirect(
|
|
new URL(`/${homeWorkspace.id}/chat`, request.url)
|
|
)
|
|
}
|
|
|
|
return response
|
|
} catch (e) {
|
|
return NextResponse.next({
|
|
request: {
|
|
headers: request.headers
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
export const config = {
|
|
matcher: "/((?!api|static|.*\\..*|_next|auth).*)"
|
|
}
|