Open Source API Gateway

500 Internal Server Error: Error Serializing JavaScript Object to JSON

Membrane API Gateway returns 500 Internal Server Error with the detail Error serializing Map to JSON when a javascript script running on the GraalVM engine returns an object that cannot be written as JSON. The script is part of the gateway configuration, so the configuration needs to be fixed, not the client or the backend.

The Error Response

The response contains the status 500 Internal Server Error, the detail Error serializing Map to JSON, the problem type https://membrane-api.io/problems/internal and a link to this page. In development mode, the message field contains the error of the JSON serializer, which names the value that could not be written. The type internal means that the gateway could not complete the processing of the message. In production mode, the title is replaced by Internal Server Error and the details are left out.

When This Error Occurs

This error only occurs with the javascript plugin on the GraalVM engine, which hands the script's result to Membrane as a JavaScript value. Membrane writes a returned object as the JSON body of the message. Errors with maps returned from other scripts are described under Error serializing Map to JSON. See the JavaScript plugin for more about scripts.

Common Causes

The Object Contains a Value That Cannot Be Serialized

The object the script returns, as its last expression or with return, contains a value that cannot be written as JSON, such as a function or a Java object without serializable properties.

The Last Expression Is an Unintended Object

The script was meant to return nothing, a string or a Response, but its last expression is an object that the script did not mean to use as the body.

How to Fix It

  1. Return only plain data from the script: objects, arrays, strings, numbers, booleans and null.
  2. To write the body yourself, return a string, for example the result of JSON.stringify(...).
  3. If the script should not change the body, make sure its last expression is not an object.
  4. Check the gateway log for the full serializer error.

Hide Details in Production

By default, Membrane runs in development mode and adds details to error responses that help you find the problem. These details may reveal information about your setup. In production, turn them off:

configuration:
production: true
configuration:
  production: true

Add the configuration document to your apis.yaml and separate it from the APIs with ---. The title then reads Internal Server Error, and the details and the link to this page are left out. If the response contains a log key, search the gateway log for it to find the full error message.

Related Documentation

Configuration reference:

Tutorials with runnable examples:

← All Membrane error messages

Still stuck? See the troubleshooting guide or ask on GitHub Issues. For commercial support, contact info@predic8.de.