This commit is contained in:
hailin 2025-06-25 16:04:13 +08:00
parent 04b5c0c94e
commit e35878178a
1 changed files with 25 additions and 15 deletions

View File

@ -1,26 +1,36 @@
// app/utility/runtime-env-provider.tsx
// app/_runtime-env-provider.tsx
import { headers } from "next/headers"
import { useServerInsertedHTML } from "next/navigation" // ✅ 改这里
import React from "react";
import { useServerInsertedHTML } from "next/navigation"
import React from "react"
export function RuntimeEnvProvider({ children }: { children: React.ReactNode }) {
/* ① 计算本次请求的 Supabase URL按你的内网场景改即可 */
const h = headers();
const proto = h.get("x-forwarded-proto") ?? "http";
const host = h.get("x-forwarded-host") ?? h.get("host"); // 内网一般就是 host
const port = process.env.SUPABASE_PORT ?? "8000";
const supabaseUrl = `${proto}://${host?.split(",")[0]}:${port}`;
export default function RuntimeEnvProvider({
children,
}: {
children: React.ReactNode
}) {
/* 1. 协议 */
const h = headers()
const proto =
h.get("x-forwarded-proto") ??
(h.get("host")?.includes(":443") ? "https" : "http")
/* ② 注入脚本:保证在 <head> 中且早于所有客户端 JS */
/* 2. 主机(域名或 IP剥离掉可能附带的端口 */
const rawHost = h.get("x-forwarded-host") ?? h.get("host")!
const hostname = rawHost.split(",")[0].split(":")[0] // 去掉逗号和端口
/* 3. 端口固定 8000 */
const supabaseUrl = `${proto}://${hostname}:8000`
/* 4. 注入行内脚本 */
useServerInsertedHTML(() => (
<script
dangerouslySetInnerHTML={{
__html: `window.RUNTIME_ENV = { SUPABASE_URL: ${JSON.stringify(
__html: `window.RUNTIME_ENV={SUPABASE_URL:${JSON.stringify(
supabaseUrl,
)} };`,
)}};`,
}}
/>
));
))
return <>{children}</>;
return <>{children}</>
}