[Fixed] Error: React Context is unavailable in Server Components – Javascript

by
Ali Hasan
django-authentication next-auth next.js reactjs

Quick Fix: Employ "getServerSession" from "next-auth/next" within the "async" "ChatbotIdPage" function, since it concerns "Server Components".

The Solutions:

Solution 1: Use getServerSession instead of useSession

In Next.js, useSession works only in Client Components (with "use client" at the top). However, the error message indicates that you are using useSession in a Server Component. Instead, you should use getServerSession to fetch the session in a Server Component. Here’s a modified version of your code:

import { getServerSession } from "next-auth/next";
import { authOptions } from "app/api/auth/[...nextauth]"; // ⚠️ Make sure this is the correct path
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 session = await getServerSession(authOptions); // Use getServerSession

  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;

With these changes, the error message should go away and your application should work as expected.

Solution 2: Add “use client” at the top of your page

In Next 13, anything that uses React.Context (even your libraries) will need to be a Client component. You can achieve this by adding "use client" at the top of your page.

After that your code should look something like:

<code>
  &quot;use client&quot; <br/>

  import { useSession } from &quot;next-auth/react&quot;; <br/>
  import prisma from &quot;@/lib/prisma&quot;; <br/>
  import { ChatbotClient } from &quot;./components/chatbot-client&quot;; <br/>
  import { redirect } from &quot;next/navigation&quot;; <br/>
  <br/>

  interface ChatbotIdPageProps { <br/>
    params: { <br/>
      chatbotId: string; <br/>
    }; <br/>
  } <br/>
  <br/>

  const ChatbotIdPage = async ({ params }: ChatbotIdPageProps) =&gt; { <br/>
    const { data: session } = useSession(); <br/>
  <br/>

    if (!session?.user) { <br/>
      redirect(&quot;/demo&quot;); <br/>
    } <br/>
  <br/>

    const userId = JSON.stringify(session.user); <br/>
  <br/>

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

    return &lt;ChatbotClient initialData={chatbot} /&gt;; <br/>
  }; <br/>
  <br/>

  export default ChatbotIdPage; <br/>
</code>

This should fix the error, and you will be able to use React.Context in your Server Component.

Q&A

What can I do when I getting an error like: React Context is unavailable in Server Components ?

Use getServerSession instead of useSession. The former works in Server Components, the latter in Client Components only.

How can I fix the problem?

You can use &quot;use client&quot; at the top of your page in Next 13.

Video Explanation:

The following video, titled "How To Fix NextJS 13's N+1 Problem - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Making React Context FAST! Jack Herrington•80K views · 6:51 · Go to channel ... Write PHP in Next.js/React Components (Server Actions). Bufferhead ...