This commit is contained in:
hailin 2025-06-25 17:11:12 +08:00
parent 072dce8517
commit d71078b262
1 changed files with 59 additions and 14 deletions

View File

@ -30,30 +30,75 @@
// lib/supabase-server.ts
// // lib/supabase-server.ts
// import { createServerClient, type CookieOptions } from "@supabase/ssr"
// import { cookies } from "next/headers"
// import { getRuntimeEnv } from "@/lib/get-runtime-env" // ← 改成新的工具函数
// import { Database } from "@/supabase/types"
// export function getSupabaseServerClient() {
// /* ① URL优先 RuntimeEnv由 RuntimeEnvProvider 注入),
// 然后退回到 .env最后兜底 localhost */
// const supabaseUrl =
// getRuntimeEnv("SUPABASE_URL") ??
// process.env.SUPABASE_URL ??
// "http://localhost:8000"
// // ✅ 打印实际使用的 Supabase URL
// console.log(`..................supabase URL in server: ${supabaseUrl}`)
// /* ② 匿名 KEY 只放 .env别暴露到 RuntimeEnv */
// const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
// if (!supabaseAnonKey) {
// throw new Error("⛔️ NEXT_PUBLIC_SUPABASE_ANON_KEY 未设置")
// }
// /* ③ Cookie 透传Next 13/14 App Router 写法) */
// const cookieStore = cookies()
// return createServerClient<Database>(supabaseUrl, supabaseAnonKey, {
// cookies: {
// get(name: string) {
// return cookieStore.get(name)?.value
// },
// set(name: string, value: string, options: CookieOptions) {
// try {
// cookieStore.set({ name, value, ...options })
// } catch {}
// },
// remove(name: string, options: CookieOptions) {
// try {
// cookieStore.set({ name, value: "", ...options })
// } catch {}
// }
// }
// })
// }
import { createServerClient, type CookieOptions } from "@supabase/ssr"
import { cookies } from "next/headers"
import { getRuntimeEnv } from "@/lib/get-runtime-env" // ← 改成新的工具函数
import { cookies, headers } from "next/headers"
import { Database } from "@/supabase/types"
export function getSupabaseServerClient() {
/* URL RuntimeEnv RuntimeEnvProvider
退 .env localhost */
const supabaseUrl =
getRuntimeEnv("SUPABASE_URL") ??
process.env.SUPABASE_URL ??
"http://localhost:8000"
function getDynamicSupabaseUrl(): string {
const h = headers()
const proto = h.get("x-forwarded-proto") ?? (h.get("host")?.includes(":443") ? "https" : "http")
const rawHost = h.get("x-forwarded-host") ?? h.get("host")!
const hostname = rawHost.split(",")[0].split(":")[0].trim()
return `${proto}://${hostname}:8000`
}
// ✅ 打印实际使用的 Supabase URL
console.log(`..................supabase URL in server: ${supabaseUrl}`)
export function getSupabaseServerClient(urlOverride?: string) {
const supabaseUrl = urlOverride ?? getDynamicSupabaseUrl()
console.log(`✅ Supabase URL [Server]: ${supabaseUrl}`)
/* ② 匿名 KEY 只放 .env别暴露到 RuntimeEnv */
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
if (!supabaseAnonKey) {
throw new Error("⛔️ NEXT_PUBLIC_SUPABASE_ANON_KEY 未设置")
}
/* ③ Cookie 透传Next 13/14 App Router 写法) */
const cookieStore = cookies()
return createServerClient<Database>(supabaseUrl, supabaseAnonKey, {