This commit is contained in:
parent
1e470bf7b5
commit
811efaef32
|
|
@ -0,0 +1,12 @@
|
|||
// lib/runtime-env/get-runtime-env-server.ts
|
||||
|
||||
export async function loadSupabaseUrl(): Promise<string | undefined> {
|
||||
const { headers } = await import("next/headers")
|
||||
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`
|
||||
}
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
// lib/runtime-env/server.ts
|
||||
import { headers } from "next/headers"
|
||||
|
||||
export function getRuntimeEnvSSR(key: string): string | undefined {
|
||||
if (key === "SUPABASE_URL") {
|
||||
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`
|
||||
}
|
||||
|
||||
return process.env[key]
|
||||
}
|
||||
|
|
@ -92,25 +92,24 @@
|
|||
// supabaseAnonKey
|
||||
// )
|
||||
|
||||
|
||||
import { createBrowserClient } from "@supabase/ssr"
|
||||
import { Database } from "@/supabase/types"
|
||||
|
||||
let supabaseUrl = "http://localhost:8000"
|
||||
|
||||
if (typeof window === "undefined") {
|
||||
try {
|
||||
const mod = require("../runtime-env/server") // ✅ 动态加载,避免 headers 被编译期扫描
|
||||
const envUrl = mod.getRuntimeEnvSSR?.("SUPABASE_URL")
|
||||
if (envUrl) {
|
||||
supabaseUrl = envUrl
|
||||
console.log("[SSR] SUPABASE_URL:", supabaseUrl)
|
||||
// ✅ SSR 时动态加载,不会触发 headers() 静态报错
|
||||
const load = async () => {
|
||||
const { loadSupabaseUrl } = await import("@/lib/runtime-env/get-runtime-env-server")
|
||||
const url = await loadSupabaseUrl()
|
||||
if (url) {
|
||||
supabaseUrl = url
|
||||
console.log("[SSR] SUPABASE_URL =", supabaseUrl)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("❌ SSR runtime-env load failed:", err)
|
||||
}
|
||||
// 注意:不能阻塞同步逻辑,只是设置变量
|
||||
load()
|
||||
} else {
|
||||
// ✅ CSR 环境:从 window 或 localStorage 获取
|
||||
const runtimeEnv = (window as any).RUNTIME_ENV
|
||||
const envUrl = runtimeEnv?.SUPABASE_URL
|
||||
|
||||
|
|
@ -124,11 +123,11 @@ if (typeof window === "undefined") {
|
|||
}
|
||||
}
|
||||
|
||||
console.log("[CSR] SUPABASE_URL:", supabaseUrl)
|
||||
console.log("[CSR] SUPABASE_URL =", supabaseUrl)
|
||||
}
|
||||
|
||||
// ✅ 创建 supabase 客户端
|
||||
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
|
||||
|
||||
export const supabase = createBrowserClient<Database>(
|
||||
supabaseUrl,
|
||||
supabaseAnonKey
|
||||
|
|
|
|||
Loading…
Reference in New Issue