Please help me fix this error: When I run the application in nextjs 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;
2
Answers
In Next 13, anything that uses React.Context (even your libraries) will need to be a Client component. You can achieve this by having "use client" at the top of your page.
Instead of
useSession
which works only in Client Components (with"use client"
at the top), usegetServerSession
since you are in a Server Component:Side note, if you try to add
"use client"
and stick withuseSession
, the component function cannot beasync
, and there you can fetch data only in auseEffect
.