Files
otunes/apps/web/components/convex-client-provider.tsx

45 lines
1.2 KiB
TypeScript

"use client"
import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs"
import { buildConvexUrl } from "@otunes/convex/server-url"
import { ConvexReactClient } from "convex/react"
import { ReactNode } from "react"
import { PersistentCacheProvider } from "@/components/persistent-cache-provider"
// Server rendering never runs Convex queries, so this URL is never contacted.
const SSR_CONVEX_URL = "http://127.0.0.1:3210"
let client: ConvexReactClient | undefined
function browserConvexUrl() {
const { host, protocol } = window.location
return buildConvexUrl(host, protocol === "https:" ? "https" : "http")
}
function getConvexClient(convexUrl: string | undefined) {
if (!client) {
client = new ConvexReactClient(
typeof window === "undefined"
? SSR_CONVEX_URL
: (convexUrl ??
process.env.NEXT_PUBLIC_CONVEX_URL ??
browserConvexUrl())
)
}
return client
}
export function ConvexClientProvider({
convexUrl,
children,
}: {
convexUrl?: string
children: ReactNode
}) {
return (
<ConvexAuthNextjsProvider client={getConvexClient(convexUrl)}>
<PersistentCacheProvider>{children}</PersistentCacheProvider> </ConvexAuthNextjsProvider>
)
}