Skip to content

[Bug]: Malformed JSON request body returns HTTP 500 (unknown_error) instead of HTTP 400 #14796

@ShehabSherif0

Description

@ShehabSherif0

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

  1. Security: A 500 leaks that a server error occurred from a client-controlled input. Clients should receive 400 for their own malformed requests.
  2. Debugging: API consumers (storefront devs, integration partners) see unknown_error and have no idea their JSON is malformed.
  3. Observability: 500s from client mistakes pollute error tracking dashboards (Sentry, etc.) with noise that should be 4xx.
  4. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions