Skip to content

Allow default hostnames for fetch() in production #8346

Description

@getaaron

Problem

I'm always frustrated when I'm making a create-react-app app that's hosted in S3 (or other static hosting) and the backend API app is hosted elsewhere.

Locally I can use

"proxy": "http://localhost:5000",

and

await fetch(`/someEndpoint`)

will proxy the request and display the results. But there's no way to provide a different default hostname for production. Unless I intervene, this code will always try to hit /someEndpoint on the static web server.

Solution I'd like

I'd like to similarly provide a hostname for production in package.json, perhaps:

"production-hostname": "https://fun-app.herokuapp.com",

or perhaps as a collection:

"hostnames": [
    "production": "https://fun-app.herokuapp.com"
]

These hostnames could be inserted into fetch() calls during compilation.

Alternatives considered

  • Hacking together something based on environment variables (a lot of cruft that we could hide from users)
  • Ejecting and making my own proxy middleware

CORS note

This approach would require that the production API (e.g. fun-app.herokuapp.com ) respond to an OPTIONS request with the appropriate Access-Control-Allow-Origin HTTP header to allow the user's browser to process the request. This should be relatively straightforward and if we implement this feature it could be discussed in documentation.

Additional context

I see lots of roughly related issues here and on Stack Overflow. Seems like hosting an API one place and then hosting the react app on a static hosting service elsewhere is a fairly common setup but we don't have the configuration options to really handle it elegantly.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions