78 lines
2.4 KiB
TypeScript
78 lines
2.4 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) {
|
|
const { pathname } = request.nextUrl
|
|
const preferredLanguage = request.cookies.get("preferred-language")?.value
|
|
|
|
console.log("[middleware] ⏩ Incoming request")
|
|
console.log("[middleware] → pathname:", pathname)
|
|
console.log("[middleware] → preferred-language from cookie:", preferredLanguage)
|
|
|
|
// 判断是否已包含语言前缀
|
|
const hasLocalePrefix = i18nConfig.locales.some(
|
|
(locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`)
|
|
)
|
|
console.log("[middleware] → hasLocalePrefix:", hasLocalePrefix)
|
|
|
|
if (
|
|
preferredLanguage &&
|
|
!hasLocalePrefix &&
|
|
(i18nConfig.locales as readonly string[]).includes(preferredLanguage)
|
|
) {
|
|
const url = request.nextUrl.clone()
|
|
url.pathname = `/${preferredLanguage}${pathname}`
|
|
console.log("[middleware] 🚀 Redirecting to preferred language:", url.pathname)
|
|
return NextResponse.redirect(url)
|
|
}
|
|
|
|
const i18nResult = i18nRouter(request, i18nConfig)
|
|
if (i18nResult) {
|
|
console.log("[middleware] ✅ i18nRouter redirect applied")
|
|
return i18nResult
|
|
}
|
|
|
|
try {
|
|
const { supabase, response } = createClient(request)
|
|
const session = await supabase.auth.getSession()
|
|
|
|
console.log("[middleware] 🔐 Supabase session:", session?.data?.session)
|
|
|
|
const redirectToChat = session && 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) {
|
|
console.error("[middleware] ❌ Home workspace not found:", error?.message)
|
|
throw new Error(error?.message)
|
|
}
|
|
|
|
const target = `/${homeWorkspace.id}/chat`
|
|
console.log("[middleware] 🏠 Redirecting to home workspace:", target)
|
|
|
|
return NextResponse.redirect(new URL(target, request.url))
|
|
}
|
|
|
|
return response
|
|
} catch (e) {
|
|
console.error("[middleware] 💥 Exception:", e)
|
|
return NextResponse.next({
|
|
request: {
|
|
headers: request.headers,
|
|
},
|
|
})
|
|
}
|
|
}
|
|
|
|
export const config = {
|
|
matcher: "/((?!api|static|.*\\..*|_next|auth).*)",
|
|
}
|