addDataAndFileToRequest returns 500 for malformed JSON request bodies
Description
The addDataAndFileToRequest() utility in packages/next/src/utilities/ calls JSON.parse() without error handling. When malformed JSON is sent to Payload's REST API or GraphQL endpoints, the parsing fails with a SyntaxError that propagates as an unhandled 500 Internal Server Error instead of returning 400 Bad Request.
This affects all auto-generated REST API endpoints and the GraphQL endpoint since they share the same body parsing utility.
Current Behavior
Sending malformed JSON (e.g., with invalid escape sequences like \x or \z) to any Payload API endpoint returns:
- HTTP Status: 500 Internal Server Error
- Error in logs:
SyntaxError: Bad escaped character in JSON at position 55 at JSON.parse (<anonymous>) at addDataAndFileToRequest (dist/utilities/addDataAndFileToRequest.js:41:...)
Expected Behavior
Malformed JSON should return:
- HTTP Status: 400 Bad Request
- Response: Structured error message indicating invalid JSON
- Logs: No stack trace (client error, not server error)
Reproduction Steps
curl -X POST https://your-app.com/api/posts \
-H "Content-Type: application/json" \
-d '{"title": "test\x"}'
Result: 500 Internal Server Error Expected: 400 Bad Request
Impact
- Incorrect HTTP semantics — client errors reported as server errors
- Noisy production logs — stack traces from bots/scanners sending malformed requests
- Monitoring pollution — can't distinguish real server issues from bad client input
- No workaround — auto-generated collection endpoints can't add custom error handling
Proposed Solution
Wrap JSON.parse() in addDataAndFileToRequest with try/catch:
try {
const data = JSON.parse(bodyText);
// ... continue processing
} catch (error) {
if (error instanceof SyntaxError) {
throw new APIError('Invalid JSON in request body', httpStatus.BAD_REQUEST);
}
throw error;
}
Related Issues
- #13410 — Fixed similar issue in v3.51.0 for missing filename case, but didn't address broader JSON parsing errors
- Next.js #86945 — Framework-level body parsing issue (still open)
Environment
- Payload: ^3.75.0
- Next.js: ^16.1.6
- Node.js: 20+
Context
Discovered during automated security assessment. Pentester sent malformed JSON to test error handling. While not a security vulnerability per se, returning 500 for client errors violates HTTP semantics and creates operational issues with logging and monitoring.
🚀 This is included in version v3.78.0
This issue has been automatically locked. Please open a new issue if this issue persists with any additional detail.