I am new to the concepts of Next.js, and I recently encountered an issue while attempting to fetch data from an API. The API is designed to check if a user session exists (i.e., if the user is logged in) and then returns a JSON response through a GET request. Below is the content of the getGoal/route.ts file which handles this API:
import { getAuthSession } from "@/lib/auth";
import { db } from "@/lib/db";
export async function GET(req: Request) {
try {
const session = await getAuthSession();
if (!session?.user) {
return new Response("User is not logged in", {
status: 401,
});
}
const userId = session.user.id;
const goals = await db.goal.findMany({
where: {
userId: userId,
},
});
return new Response(JSON.stringify(goals), {
status: 200,
});
} catch (error) {
console.error(error);
return new Response("Internal Server Error", {
status: 500,
});
}
}
When I access this code through my browser at http://localhost:3000/api/getGoal, it correctly displays either "User not logged in" or the JSON data based on the user's login status. However, when I attempt to fetch this API in my page.tsx file:
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>
);
};
Surprisingly, regardless of whether the user is logged in or not, the data.status
always shows as 200 and the data is always displayed. This behavior has left me confused, as I feel like I may be missing something crucial here.
Despite trying various approaches such as different catch clauses and seeking guidance from tutorials and chatbots, I have been unable to resolve the issue. My expectation is for the data to be shown only if a user is logged in and there is an active session.