JakobHoeg
JakobHoeg

Reputation: 21

NextJS - API route always returns status code 200

Fairly new to nextjs, and I've come across an issue when trying to fetch an api. The API itself is fairly simple and checks if there is a session (user is logged in) and then returns a JSON with a GET. This is the getGoal/route.ts API file:

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,
        });
    }
}

If i access this code in my browser http://localhost:3000/api/getGoal, it returns the 401 message with User not logged in, if im not logged in and it returns the json if I am logged in. However, if i then try and fetch this API in my page.tsx:

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>
    );
};

And if I console.log the data.status, it always returns a status code of 200 and always shows the data. I think I'm missing something here, but I just can't seem to wrap my head around it. Again, I am fairly new to Nextjs and React in general.

I've tried different types of catch clauses. I've tried asking chatgpt. I've tried looking around for tutorials. I expect it to show the data only if a user is logged in (there is a session).

Upvotes: 2

Views: 4682

Answers (1)

Vikram Ray
Vikram Ray

Reputation: 1146

You can use NextResponse as mentioned in nextjs doc.


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,
    });
  }
}

Upvotes: 0

Related Questions