next.jsresponsenext-routernextjs-api-router

NextResponse returning 200 while the response from the endpoint is 400


I was using Route Handler for fetching from external endpoint. The external endpoint is returning status 400 or any error, but when I locally hit API from the client component (e.g /api/route.ts) I got a status of 200 but the response is 400 otherwise it doesn't go to catch(error).

Are there any ways to resolve this?

Thank you.

I try to use NextResponse.next() inside the route handler but it says that .next() couldn't be inside the route handlers. I am expecting it to be "transparent" so that the error returned is match with the response from external endpoint.

/api/something

export async function POST(req: Request) {
  const something: DataInterface = await req.json();
  const data = something.requestData;

  try {
    const res = await instance.post(
    `i hit the endpoint here`,
    data,
    {
      headers: {' some header '}
    });

  const { output_schema } = res.data;

  const generateUrl = `i generate some url here`;

  const response = { output_schema, generateUrl };

  return NextResponse.json(response);
 } catch (error) {
   return NextResponse.json(error);
 }
}

/app/something

try {
  const { data } = await axios.post("/api/something", {
    requestData,
  });
  const { generateUrl, ...output_shema } = data;
  setUrl(generateUrl);
  setResponse(output_shema);
} catch (error) {
  setResponse(error);
} finally {
  setIsLoading(false);
}

Solution

  • In your catch blog of the route handler, you need to specify the status, as by default Next.js would use a 200.

    return NextResponse.json(error, { status: 400 });
    

    If the error object contains enough information, you can set the status dynamically, something like:

    return NextResponse.json(error, { status: error.response.status });