Issues calling an API endpoint from React custom component?

Hey @asehmi, it sounds like your endpoint’s CORS response probably doesn’t handle the “null” origin. Currently, the Streamlit component iframe sandbox omits the “allow-same-origin” flag for security reasons, which means that the component is mounted in its iframe with a “null” origin. That is: your component’s origin is the string literal “null”. Some (many!) endpoints don’t handle this.

To fix it, you need to set an Access-Control-Allow-Origin: null header on your endpoint’s response. (Note that Access-Control-Allow-Origin: * will not work here - the “*” wildcard doesn’t handle the null origin.)

Here’s an example Flask app that demonstrates it:

import flask

app = flask.Flask(__name__)


@app.route("/api/ping")
def ping():
    return "pong!"


@app.after_request
def after_request(response):
    # If the request comes from a sandboxed iframe, the origin will be
    # the string "null", which is not covered by the "*" wildcard.
    # To handle this, we set "Access-Control-Allow-Origin: null".
    response.headers.add(
        "Access-Control-Allow-Origin",
        "null" if flask.request.origin == "null" else "*")
    response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
    response.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
    return response

(Oh, worth noting: we have some upcoming plans that should mitigate some of this pain. Because it’s a huge pain!)

2 Likes