diff --git a/chatdesk-ui/lib/runtime-env/get-runtime-env-server.ts b/chatdesk-ui/lib/runtime-env/get-runtime-env-server.ts new file mode 100644 index 0000000..2712257 --- /dev/null +++ b/chatdesk-ui/lib/runtime-env/get-runtime-env-server.ts @@ -0,0 +1,12 @@ +// lib/runtime-env/get-runtime-env-server.ts + +export async function loadSupabaseUrl(): Promise { + 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` +} diff --git a/chatdesk-ui/lib/runtime-env/server.ts b/chatdesk-ui/lib/runtime-env/server.ts deleted file mode 100644 index 8d4069e..0000000 --- a/chatdesk-ui/lib/runtime-env/server.ts +++ /dev/null @@ -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] -} diff --git a/chatdesk-ui/lib/supabase/browser-client.ts b/chatdesk-ui/lib/supabase/browser-client.ts index 8491f5a..5aed37f 100644 --- a/chatdesk-ui/lib/supabase/browser-client.ts +++ b/chatdesk-ui/lib/supabase/browser-client.ts @@ -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( supabaseUrl, supabaseAnonKey