Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: React Context is unavailable in Server Components

Please help me fix this error: When I run the application in Next.js I am getting this message:

Error: React Context is unavailable in Server Components

import { useSession } from "next-auth/react";
import prisma from "@/lib/prisma";
import { ChatbotClient } from "./components/chatbot-client";
import { redirect } from "next/navigation";

interface ChatbotIdPageProps {
  params: {
    chatbotId: string;
  };
}

const ChatbotIdPage = async ({ params }: ChatbotIdPageProps) => {
  const { data: session } = useSession();

  if (!session?.user) {
    redirect("/demo");
  }

  const userId = JSON.stringify(session.user);

  const chatbot = await prisma.chatbot.findUnique({
    where: {
      id: params.chatbotId,
      userId: userId,
    },
  });

  return <ChatbotClient initialData={chatbot} />;
};

export default ChatbotIdPage;
like image 852
Victor Timi Avatar asked May 13 '26 13:05

Victor Timi


1 Answers

In my case, I had to

  • Create a Separate Client Component for SessionProvider.

  • Create a new file, for example, providers.tsx, and define a client component that wraps its children with SessionProvider. This component should be marked with 'use client'.

      // providers.tsx
      "use client";
      import { SessionProvider } from "next-auth/react";
    
      export function Providers({ children }: { children: React.ReactNode }) {
        return <SessionProvider>{children}</SessionProvider>;
      }
    
  • Then, in your layout.tsx, import and use this Providers component to wrap your application or the part of your application that needs access to the session.

      // layout.tsx
      import { Providers } from "./providers";
    
      export default function RootLayout({
       children,
      }: {
       children: React.ReactNode;
      }) {
       return (
          <html lang="en">
            <body>
              <Providers>{children}</Providers>
            </body>
          </html>
       );
      }
    
like image 146
sundayonah Avatar answered May 15 '26 01:05

sundayonah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!