NextJS API routes consistently provide a status code of 200 upon execution

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.

Answer №1

If you're looking for a reliable solution, consider utilizing NextResponse as outlined in the official documentation.


import { NextResponse } from "next/server";
export async function GET(req: Request) {
  try {
    // Implement your code here
    const goals = {};
    return NextResponse.json(goals, {
      status: 200,
    });
  } catch (error) {
    // Ensure to handle any potential errors that may arise
    console.error(error);
    return NextResponse.json({"error": "Internal Server Error"}, {
      status: 500,
    });
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with redundant code while updating state in ReactJS - React JS

Currently, I am working on a prayer times web app using reactJS (nextjs). To achieve this, I first fetch the geolocation coordinates and then retrieve the city and country name based on these coordinates. Following that, I obtain the prayer times for the s ...

Guidelines for implementing a seamless transition effect on elements with Tailwind CSS

I successfully created a responsive nav bar using Tailwind CSS in Next.js, and it is functioning perfectly. https://i.stack.imgur.com/yTCbs.png https://i.stack.imgur.com/rdXhL.png https://i.stack.imgur.com/J8fM6.png Everything works well, except when I ...

Expo app crashes when using React Native/Expo combined with Next.js (Error: Variable "React" not found in withExpoRoot.js)

I am facing an issue with my React Native/Expo + Next.js app that I built using the command npx create-next-app -e with-expo. To view the full code, visit: https://github.com/tomsoderlund/reactnative-nextjs-template The app functions properly as a web ap ...

The partial template is not functioning as anticipated

Introducing an interface designed to accept two templates, with the resulting function being a partial of one of them (similar to React-Redux): export type IState<TState, TOwnProps> = { connect: (mapStateToProps: MapStateToProps<TState, Parti ...

Tips for implementing react-hook-form in an Ionic Modal?

I've been experimenting with implementing react-hook-form in my Ionic React project. Here's a simple form I created: const CustomForm: React.FC<{ color: string }> = ({ color }) => { const { handleSubmit, register } = useForm(); con ...

Why does it display 'Undefined' when I attempt to access an object in an array in Next.js?

I am currently working on a way to display sub Products related to the main product. I have attempted to extract the product code from the URL and then retrieve sub-products that correspond to the main product code. List of Products and Sub products const ...

Error encountered in Angular 2 with RXJS Observable: Unable to call function catch() on this.http.get(...).map(...) due to TypeError

Everything was running smoothly with my Service until today, when I encountered the following error: TypeError: this.http.get(...).map(...).catch is not a function. Upon debugging the code, it crashes at the catch method. import { Test } from "./home.c ...

The @output decorator in Angular5 enables communication between child and

Hello fellow learners, I am currently diving into the world of Angular and recently stumbled upon the @output decorators in angular. Despite my best efforts to research the topic, I find myself struggling to fully grasp this concept. Here's a snippet ...

Enhance Vue TypeScript components with custom component-level properties

In my vue2 project, I am utilizing vue-class-component along with vue-property-decorator. My goal is to implement component-level security validation for each component when it loads. I imagine implementing it with a signature like this: @Component @Secur ...

Resolving type error issues related to using refs in a React hook

I have implemented a custom hook called useFadeIn import { useRef, useEffect } from 'react'; export const useFadeIn = (delay = 0) => { const elementRef = useRef<HTMLElement>(null); useEffect(() => { if (!elementRef.current) ...

What is the best way to incorporate dynamic infographics into an ionic app?

Looking to design unique infographics for my ionic app, similar to the ones seen here: Any recommendations on tools or strategies for creating these infographics? ...

Typescript is asserting that the React class component has a property, despite what the component itself may suggest

I'm running into an issue with React refs and class components. Here's my simplified code snippet. I have a component called Engine with a property getInfo. In my test, I check for this.activeElement &&, which indicates that it's no ...

Retrieve component information from the service

Incorporated within my component is a form that I'm utilizing with reactive form and my intention is to reach this form through my service. For example: const id = MyComponent.id and inside my component: @Output: public id: number = 7; ...

Unable to reset input in a functional component using React JS

I have a component named TextInput that is responsible for rendering an input element: function TextInput({ type = "text", label, name, required = false }) { const [value, setValue] = useState(""); function handleChange(e) { se ...

Angular2 Animation for basic hover effect, no need for any state change

Can anyone assist me with ng2 animate? I am looking to create a simple hover effect based on the code snippet below: @Component({ selector: 'category', template : require('./category.component.html'), styleUrls: ['./ca ...

Is there a way for me to obtain a selection of 20 random items from this JSON data

When working with my JSON data using Myjson.slice(1, 20), I encountered a situation where I needed to extract only 20 items from a dataset that had a length of 2624. In the code snippet provided, I attempted to use the slice method but struggled to differe ...

My Next.js Image component is failing to display my images

Having trouble with my Next.js Image component. Despite trying various solutions, my images still won't load. <div> {output?.map((item) => ( <div> {console.log(`${apiUrl}${item.localImage}`)} <Image loader={ ...

``Can someone provide guidance on how to showcase the validation check result for a text-field in the snackbar using Vuet

One of the challenges I'm facing in my project is implementing a validation function for the customer form. While using the vuetify validate method would be the easy way to go, I need to display the validation messages both as snackbar and next to eac ...

How can we ensure a generic async function with a return type that is also generic in Typescript?

I'm currently working on a function that retries an async function multiple times before rejecting. I want to make sure the typescript typings of the retry function are maintained and also ensure that the passed function is of type PromiseLike. Creat ...

I'm experiencing an issue with hot reloading on my Nextjs project while using MacOs

I've been trying to find a solution to my issue, but so far, no luck. A colleague handed me a NextJs project (built with React), and after running yarn install followed by yarn run dev, I noticed that the server starts successfully. However, whenever ...