42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
"use client";
|
||||
|
|
|
|||
|
|
import { ReactNode, useState } from "react";
|
|||
|
|
import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs";
|
|||
|
|
import { ConvexReactClient } from "convex/react";
|
|||
|
|
|
|||
|
|
interface ConvexClientProviderProps {
|
|||
|
|
children: ReactNode;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Convex 客户端 Provider(包含 Auth)
|
|||
|
|
*/
|
|||
|
|
export function ConvexClientProvider({ children }: ConvexClientProviderProps) {
|
|||
|
|
const [convex] = useState(() => {
|
|||
|
|
// 动态获取 Convex URL,默认优先使用环境变量。
|
|||
|
|
// 说明:浏览器侧优先用当前 hostname(端口固定 3210),避免通过非 localhost/127 访问前端时出现跨域/白名单不匹配。
|
|||
|
|
const getConvexUrl = () => {
|
|||
|
|
// 默认使用环境变量
|
|||
|
|
const envUrl = process.env.NEXT_PUBLIC_CONVEX_URL;
|
|||
|
|
if (typeof window === "undefined") {
|
|||
|
|
return envUrl || "http://127.0.0.1:3210";
|
|||
|
|
}
|
|||
|
|
// 在浏览器中,使用当前主机名,但端口改为 3210
|
|||
|
|
const hostname = window.location.hostname;
|
|||
|
|
return `http://${hostname}:3210`;
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
const convexUrl = getConvexUrl();
|
|||
|
|
if (!convexUrl) {
|
|||
|
|
throw new Error("NEXT_PUBLIC_CONVEX_URL is not defined");
|
|||
|
|
}
|
|||
|
|
return new ConvexReactClient(convexUrl);
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
return (
|
|||
|
|
<ConvexAuthNextjsProvider client={convex}>
|
|||
|
|
{children}
|
|||
|
|
</ConvexAuthNextjsProvider>
|
|||
|
|
);
|
|||
|
|
}
|