#Next Server JSON parsing error

1 messages · Page 1 of 1 (latest)

grizzled krakenBOT
#

Hi @tepid cobalt. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the error message you provided, it seems like the response from the fetch request to process.env.WEBHOOK_URL is not returning a valid JSON object. The Unexpected end of JSON input error typically occurs when JSON.parse() or res.json() is called on an empty document or a document with an improper format.

In the context of Next.js, this error can occur when you're trying to parse the response of a fetch request that doesn't return a JSON object.

Here's a modified version of your code that checks if the response is ok before trying to parse it:

export async function POST(request: Request) {
 const res = await fetch(process.env.WEBHOOK_URL, {
  method: 'POST',
  headers: {
   'Content-Type': 'application/json',
  },
  body: JSON.stringify({ username: 'test132', content: 'text' }),
 });

 if (!res.ok) {
  throw new Error(`HTTP error! status: ${res.status}`);
 }

 const product = await res.json();

 return Response.json({ product });
}

This code will throw an error if the response status is not ok (status is not in the range 200-299), which might help you debug the issue.

If the error persists, you might want to check the API you're calling to ensure it returns a valid JSON object. You can do this by logging the response text before trying to parse it:

console.log(await res.text());

This will print the raw response text, which might give you a clue as to why it's not parsing as JSON.

Please note that the information provided is based on general knowledge about Next.js and JavaScript, and not on the specific extracts provided.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@tepid cobalt kapa.ai is still learning and improving, please let us know how it did by reacting below

tepid cobalt
#

but the request gets perfomed tho, the webhook gets triggered

#

@grizzled kraken

grizzled krakenBOT
#

Let me check the knowledge base for you. One moment! :books: