Hey everyone, I’m struggling with a Hugo site on Netlify that uses Mailgun-js for form handling. My contact function isn’t working right and I’m getting JSON errors. Here’s what I’m seeing in the logs:
Jun 24, 12:57:15 PM: 7af5f746 ERROR Invoke Error {"errorType":"SyntaxError","errorMessage":"Unexpected end of JSON input",...}
When I take out the JSON.parse, I get this instead:
{"errorType":"SyntaxError","errorMessage":"Unexpected token b in JSON at position 0","trace":["JSON.parse ()",...
I’m totally lost on how to fix this. The code used to work fine before. It’s a basic setup with Mailgun for sending emails. Any ideas what could be causing these JSON errors? I’ve tried looking at the event.body but I’m not sure what I’m doing wrong. Help would be much appreciated!
I’ve dealt with similar JSON parsing headaches in Netlify functions before. One thing that’s helped me is adding a try-catch block around the JSON.parse() call. This way, you can log the raw event.body when parsing fails, giving you a clearer picture of what’s coming in.
Here’s a quick snippet that might help:
try {
const data = JSON.parse(event.body);
// rest of your code
} catch (error) {
console.error('Failed to parse JSON:', error);
console.log('Raw event body:', event.body);
return { statusCode: 400, body: 'Invalid JSON' };
}
This approach has saved me hours of debugging. Also, double-check your form’s enctype attribute - it should be ‘application/json’ if you’re expecting JSON data. If it’s set to ‘multipart/form-data’ or ‘application/x-www-form-urlencoded’, that could explain the parsing issues you’re seeing.
Lastly, ensure your Netlify function is set up to handle POST requests correctly. Sometimes, a mismatch in the expected request method can cause weird behavior.
I’ve encountered similar issues with Netlify and Mailgun integration before. It sounds like there might be a problem with how the form data is being sent or processed. Have you checked if the form is correctly submitting data in the expected format? Sometimes, changes in the form structure or submission process can lead to unexpected JSON parsing errors.
One thing you could try is to log the raw event.body before attempting to parse it. This might give you insight into what data is actually being received by your function. Also, ensure that your Mailgun API key and domain settings are still correct in your Netlify environment variables.
If the issue persists, you might want to consider using Netlify’s built-in form handling as a temporary workaround while you debug the Mailgun integration. This could help isolate whether the problem is with the form submission itself or the Mailgun processing.
yo, i had a similar issue. try loggin the event.body before parsin. sometimes netlify messes with the data. also, check ur form’s ‘enctype’ - should be ‘application/json’. if it aint, that could explain the weird errors. good luck mate!