NextJs 13 - NextAuth API Route session does not work

My goal is to getData() from Next API endpoint “http://localhost:3000/api/user/profile” when i visit “http://localhost:3000/profile/update” page.

My problem is when i invoke getData() to fetch data from API but it does not work.

In my API route src/app/api/user/profile/route.ts , i do not get any session from “getServerSession()” when i tried getData() on page.tsx.

But when i paste “http://localhost:3000/api/user/profile” into browser url i get session and data but not from getData() on page.tsx.

So now i dot not understand what i have done wrong and how to solve this issue. Please help.


src/app/api/user/profile/route.ts

import { authOptions } from "@/libs/auth";
import { prisma } from "@/libs/prisma";
import { getServerSession } from "next-auth/next";
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest, res: NextResponse) {
  try {
    // ❌ I can not get session when i send fetch request this route "http://localhost:3000/api/user/profile" from page.tsx that is not using "use client".
    // ✅ And also, I can get the session when i put "http://localhost:3000/api/user/profile" this url in the browser.

    const session = await getServerSession(authOptions);
    console.log(session);

    if (!session?.user) {
      return new NextResponse(
        JSON.stringify({
          status: "error",
          message: "Not authorized to access this resource",
        }),
        { status: 401 }
      );
    }

    const profile = await prisma.profile.findUnique({
      where: {
        userId: session?.user?.id,
      },
    });

    return new NextResponse(
      JSON.stringify({
        status: "ok",
        data: profile,
      }),
      { status: 200 }
    );
  } catch (error: any) {
    console.log(error);
  }
}

src/app/profile/update/page.tsx

import { getCurrentUser } from "@/actions/";
import ProfileUpdateForm from "@/components/auth/form/ProfileUpdateForm";
import { redirect } from "next/navigation";

// ❌❌ here is the problem
async function getData() {
  const res = await fetch("http://localhost:3000/api/user/profile", {
    cache: "no-store",
    credentials: "include",
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  });

  if (!res.ok) {
    console.error("Failed to fetch user profile!");
  }
  return res.json();
}

const ProfileUpdatePage = async () => {
  const user = await getCurrentUser();
  if (!user) {
    redirect("/signin?callbackUrl=/profile");
  }

  const data = await getData();

  return (
      <div>
    {JSON.stringify(data, null, 2)}
      </div>
  );
};

export default ProfileUpdatePage;

I’m currently experiencing this too in my code. Please how did you later solve it