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

Ensuring React Canvas dimensions match parent div in Konva Package - a practical guide

Placing a div in A4 format within a fixed div with a height of 500px and dynamic width, allowing scrollability, poses a challenge when inserting a Stage using the Konva library inside the A4 div. The issue arises from the stage only accepting numeric value ...

The Swiper JS component is experiencing flickering and is not functioning properly within the Next JS 13 app router

I'm currently facing some challenges with integrating a simple swiper into my Next.js website (v13 with app router). Initially, I attempted to import the swiper as usual by copying the code from a demo on their official website. While the swiper show ...

Creating a Dynamic Example in Scenario Outline Using Typescript and Cypress-Cucumber-Preprocessor

I have a question that is closely related to the following topic: Behave: Writing a Scenario Outline with dynamic examples. The main difference is that I am not using Python for my Gherkin scenarios. Instead, I manage them with Cypress (utilizing the cypre ...

Caution: An invalid next.config.js file has been detected while running the Next.js project

Whenever I try to run my project, I encounter the following three warnings: 1- warn - We found some invalid options in your next.config.js file. The property webpack5 is not recognized and may cause issues (allowed properties are: amp, analyticsId, assetP ...

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

Stop the instantiation of type alias

Is there a way to restrict the creation of an instance of a type alias, such as ValidatedEmail? type ValidatedEmail = { address: string; validatedOn: Date } Let's say we have functions validateEmail and sendEmail. const validateEmail = (email): Valid ...

What type of value does a `use` directive return?

Upon reviewing the svelte tutorial, I observed that the clickOutside function provides an object with a destroy method. What should be the precise return type of a custom use directive? export function clickOutside(node: HTMLElement): ??? { // Initia ...

Exploring Appsetting Configuration in AppModule of Angular 8

I'm looking to update my configuration in the appsettings file by replacing a hardcoded string with a reference to the appsetting. Currently, I have this hardcoded value in appmodule.ts: AgmCoreModule.forRoot({ apiKey: 'testtesttest', li ...

What is the best way to create two MUI accordions stacked on top of each other to each occupy 50% of the parent container, with only their contents scrolling

I am looking to create a layout with two React MUI Accordions stacked vertically in a div. Each accordion should expand independently, taking up the available space while leaving the other's label untouched. When both are expanded, they should collect ...

incorrect indexing in ordered list

I am facing an issue with the ngIf directive in Angular. My objective is to create a notification system that alerts users about any missing fields. Here's a stackblitz example showcasing the problem: https://stackblitz.com/edit/angular-behnqj To re ...

What steps should be taken to set up a Next.js project for transpiling a monorepo project using the next bundle analyzer tool?

I am having trouble configuring the Next.js bundle analyzer with transpiling in a monorepo project. I encountered an error message related to a loader, so I followed the instructions on Stack Overflow, but the error persists. How can I properly configu ...

Encountering a Next-auth issue while attempting to access a provider

I encountered an issue while attempting to retrieve provider data in the login component: TypeError: (0 , next_auth_react__WEBPACK_IMPORTED_MODULE_3__.providers) is not a function Here is my code along with a simple test to fetch the provider data import ...

Try fetching new data with React Query by refetching

Whenever a button is clicked, I attempt to fetch new data by calling Refetch. const {refetch,data,isLoading} = useQuery( "getkurs",() =>fetch( `https://free.currconv.com/api/v7/convert? q=${selected.country.currencyId}_IDR&compa ...

Exploring the integration of Styled-components in NextJs13 for server-side rendering

ERROR MESSAGE: The server encountered an error. The specific error message is: TypeError: createContext only works in Client Components. To resolve this issue, add the "use client" directive at the top of the file. More information can be found here i ...

Adjust the border color of the <input> element when it is clicked on

I'm currently working on a login screen for my next.js application and I've encountered an issue where the border color changes to a mixture of white and blue when I select an input field. https://i.stack.imgur.com/R2yKa.png I attempted to reso ...

Enforcement of static methods in Typescript abstract classes is not mandatory

In my TypeScript code, I have a simple structure defined: abstract class Config { readonly NAME: string; readonly TITLE: string; static CoreInterface: () => any } class Test implements Config { readonly NAME: string; readonly TITL ...

Determine data types for functions in individual files when using ElysiaJS

Currently, I am utilizing ElysiaJS to establish an API. The code can be found in the following open-source repository here. In my setup, there are three essential files: auth.routes.ts, auth.handlers.ts, and auth.dto.ts. The routes file contains the path, ...

Error in Next.js - missing property "children" in type {}

When using react and nextjs, I encountered an issue with my code that resulted in an error regarding the children prop. The error message states "Property children does not exist on type {}". Below is the snippet of code causing the error: import { NextPag ...

I am looking to change the state of only the element that is being moused over in a React Hooks useState function, rather than changing the

Currently, I have a component from line 61-67 that controls the state of an editIcon. The issue is that it changes the state values for all items in the column, rather than just the specific item or row it should apply to. When hovering over a span element ...

Is there a way to adjust React states directly in the browser without relying on React dev tools?

Recently, my website was compromised and an individual was able to manipulate the react states, gaining access to sensitive information such as an admin panel. In addition, they were able to alter the userID within the useState function, resulting in a co ...