Running nextjs 13.5.3 and implementing an API route handler under /app
This route handler mainly fetches data from a CMS and then returns the response. The IDs on the client side are hashed, so one of the functions is to unhash the IDs from a request and then hash them again in the response. Currently, for debugging purposes, I am manually changing the ID values from integers to strings, bypassing the hashing function.
Issue
Everything works fine when the response is not modified. However, if I change the ID value in the route handler (for hashing), the browser fails to parse the JSON response when using
const data = await response.json();
Uncaught (in promise) SyntaxError: Expected ':' after property name in JSON at position 2269 (line 1 column 74)
Simplified Version of Route Handler
export async function POST(request, params) {
const serviceRes = await fetch('https://someservice.com/api');
... check status of response is ok ...
... check if json is returned and if it is, parse it ...
const serviceData = await serviceRes.json();
// Modifying the ID value if it exists
if (serviceData && serviceData.data && serviceData.data.id) {
serviceData.data.id = 'test';
}
const res = NextResponse.json(serviceData, {
status: serviceRes.status,
headers: serviceRes.headers,
});
return res;
}
Updated serviceData sample after changing the ID
{
"data": {
"id": "asdasd", // originally an integer, like 4278
"title": "Hello World",
"content": "This is a test content",
"tagging": []
}
}
Further Testing
After modifying serviceData.data.id within the route handler, I added:
console.log("serviceData", serviceData);
console.log("stringified", JSON.stringify(serviceData));
No issues were seen with the object or JSON. They were validated successfully. Is there a problem with Nextresponse.json?
The error message indicates the issue occurs at the final key, tagging, where the colon appears. Despite appearing correctly in the console logs, the error suggests otherwise. Since tagging is not being altered, this is unexpected.
I attempted non-mutating versions using spread operators, but the same error persisted.
If no values in serviceData are modified, the browser can parse the JSON without any issues. This situation has me confused.