-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Description
Bug Description
Sending a Content-Type: application/json request with a malformed (non-parseable) JSON body to any Medusa API endpoint returns HTTP 500 with an opaque unknown_error response, instead of the correct HTTP 400 Bad Request.
This affects all routes — both /store/* and /admin/*.
Steps to Reproduce
# Store endpoint
curl -X POST http://localhost:9000/store/carts \
-H "x-publishable-api-key: <your_key>" \
-H "Content-Type: application/json" \
-d 'this is not valid json{'
# Admin endpoint (same result)
curl -X POST http://localhost:9000/admin/products \
-H "Content-Type: application/json" \
-d '{ broken json'Actual Behavior
HTTP 500:
{
"code": "unknown_error",
"type": "unknown_error",
"message": "An unknown error occurred."
}Expected Behavior
HTTP 400:
{
"type": "invalid_data",
"message": "Invalid JSON in request body"
}Root Cause
Express's json() body parser middleware throws a SyntaxError when it encounters invalid JSON. Medusa's global error handler does not specifically catch SyntaxError from body parsing, so it falls through to the generic unknown_error / 500 handler.
The fix is to detect Express body-parser SyntaxError (which has type === 'entity.parse.failed') in the error middleware and return 400:
// In the error handler middleware
if (err instanceof SyntaxError && (err as any).type === 'entity.parse.failed') {
return res.status(400).json({
type: "invalid_data",
message: "Invalid JSON in request body",
});
}Why This Matters
- Security: A 500 leaks that a server error occurred from a client-controlled input. Clients should receive 400 for their own malformed requests.
- Debugging: API consumers (storefront devs, integration partners) see
unknown_errorand have no idea their JSON is malformed. - Observability: 500s from client mistakes pollute error tracking dashboards (Sentry, etc.) with noise that should be 4xx.
- Standards compliance: RFC 9110 / HTTP semantics: malformed request bodies are a client error (4xx), not a server error (5xx).
Affected Versions
Confirmed on @medusajs/medusa@2.13.1. Likely affects all v2 versions since this is a framework-level error handler concern.
Environment
@medusajs/medusa |
2.13.1 |
| Node.js | v22.17.1 |
| Database | PostgreSQL 15 |
| OS | Windows 11 |