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

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

Leave a Reply