🐡

【Convex】NextJs14 と Convex【#4Convex Client Provider】

2024/03/26に公開

【#4Convex Client Provider】

YouTube: https://youtu.be/XneWwcVW8FQ

https://youtu.be/XneWwcVW8FQ

今回はConvexとClerkを連携するプロバイダーの実装を行います。

https://docs.convex.dev/auth/clerk

my-app/conponents/providers/convex-client-provider.tsx
"use client";

import { ClerkProvider, useAuth } from "@clerk/nextjs";
import {
  AuthLoading,
  Authenticated,
  ConvexReactClient,
  Unauthenticated,
} from "convex/react";
import { ConvexProviderWithClerk } from "convex/react-clerk";

const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL!;
const convex = new ConvexReactClient(convexUrl);

interface Props {
  children: React.ReactNode;
}

export const ConvexClientProvider = ({ children }: Props) => {
  return (
    <ClerkProvider>
      <ConvexProviderWithClerk useAuth={useAuth} client={convex}>
        <Authenticated>{children}</Authenticated>
        <Unauthenticated>logged out</Unauthenticated>
        <AuthLoading>Loading...</AuthLoading>
      </ConvexProviderWithClerk>
    </ClerkProvider>
  );
};
my-app/layout.tsx
import { Suspense } from "react";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { ConvexClientProvider } from "@/components/providers/convex-client-provider";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <Suspense fallback={"Loading..."}>
          <ConvexClientProvider>{children}</ConvexClientProvider>
        </Suspense>
      </body>
    </html>
  );
}

Discussion