Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the request to NextJS api route inside app directory gives 500 response code?

When I try to call my API route I receive a 500 code Internal Server Error

Place of making the request

export const fetchSuggestion = async () => {
    const response = await fetch('/api/getSuggestion', { cache: 'no-store' })
    const data = await response.json()

    return data
}

Place of calling the fetcher

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const {
    data: suggestion,
    isLoading,
    isValidating,
    mutate,
  } = useSWR('/api/getSuggestion', fetchSuggestion, { revalidateOnFocus: false })

Api route itself

export async function GET(request: Request) {
    // Connect to mcrft azure func endpoint
    const response = await fetch(`${process.env.VERCEL_URL || 'http://localhost:7071'}/api/getChatGPTSuggestion`, {
        cache: 'no-store'
    })

    const textData = await response.text()

    return new Response(JSON.stringify(textData.trim()), {
        status: 200
    })
}

File sctructure

app>api>getSuggestion>route.ts

lib>fetchSuggestion.ts

I tried to change the app/api folder with pages/api like in previous version of Next, but it didn’t work, checked if all inside the route is ok, and it is, but I don’t really understand why it gives me 500 code.

>Solution :

most likely your fetching logic is failing:

const response = await fetch(`${process.env.VERCEL_URL || 'http://localhost:7071'}/api/getChatGPTSuggestion`, {
        cache: 'no-store'
    })

you should write the logic inside try/catch block

export async function GET(request: Request) {
  try {
    // Connect to mcrft azure func endpoint
    const response = await fetch(
      `${
        process.env.VERCEL_URL || "http://localhost:7071"
      }/api/getChatGPTSuggestion`,
      {
        cache: "no-store",
      }
    );

    const textData = await response.text();

    return new Response(JSON.stringify(textData.trim()), {
      status: 200,
    });
  } catch (error) {
    console.log("error inside get route",error)
    if (error instanceof Error) {
      return new Response(error.message, { status: 500 });
    }

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading