typescript - NextJS - API rotası her zaman durum kodu 200 döndürüyor


Nextjs'e oldukça yeniyim ve bir API çağırmaya çalışırken bir sorunla karşılaştım. API'nin kendisi oldukça basit ve bir oturumun olup olmadığını kontrol ediyor (kullanıcı giriş yapmış mı) ve ardından bir GET ile JSON döndürüyor. Bu, getGoal/route.ts API dosyası:

import { getAuthSession } from "@/lib/auth";
import { db } from "@/lib/db";

export async function GET(req: Request) {
    try {
        // Get the user session using NextAuth.js getAuthSession function
        const session = await getAuthSession();

        if (!session?.user) {
            // User is not logged in, return an error response
            return new Response("User is not logged in", {
                status: 401, // Unauthorized
            });
        }

        // Retrieve user ID from the session object
        const userId = session.user.id;

        // Fetch goals associated with the user ID
        const goals = await db.goal.findMany({
            where: {
                userId: userId,
            },
        });

        return new Response(JSON.stringify(goals), {
            status: 200,
        });
        
        
    } catch (error) {
        // Handle any other errors that occur during the request
        console.error(error);

        return new Response("Internal Server Error", {
            status: 500,
        });
    }
}

Eğer tarayıcımda bu koda erişirsem http://localhost:3000/api/getGoal, oturum açmamışsam Kullanıcı giriş yapmamış mesajı ile 401 döner ve oturum açtıysam json döner. Ancak, sonra bu API'yi page.tsx içinde almaya çalışırsam:

import ProgressBar from '@/components/ProgressBar';

async function getData() {

  const data = await fetch('http://localhost:3000/api/goal')
  console.log(data.status)
  
  if (data.status !== 200) {
    throw new Error(data.statusText)
  }

  return data.json()


}


export default async function Home(){


    const goals = await getData()

    return (
      <div className='flex justify-center items-center'>
        <ProgressBar goals={goals} />
      </div>
    );
};

Ve eğer console.log ile data.status öğesini yazdırırsam, her zaman 200 durum kodu döner ve sürekli olarak veriyi gösterir. Sanırım burada bir şeyi kaçırıyorum ama bunu bir türlü anlayamıyorum. Yine de, genel olarak Nextjs ve React konusunda oldukça yeniyim.

Farklı türde catch bloklarını denedim. ChatGPT'ye sormayı denedim. Eğitim videoları aramayı denedim. Verilerin yalnızca bir kullanıcı giriş yapmışsa (bir oturum varsa) gösterilmesini bekliyorum.

Cevap #1

Nextjs dokümanında belirtildiği gibi NextResponse'u kullanabilirsiniz.

import { NextResponse } from "next/server";
export async function GET(req: Request) {
  try {
    // ... you code
    const goals = {};
    return NextResponse.json(goals, {
      status: 200,
    });
  } catch (error) {
    // Handle any other errors that occur during the request
    console.error(error);
    return NextResponse.json({"error": "Internal Server Error"}, {
      status: 500,
    });
  }
}