facebook / create-react-app

Set up a modern web app by running one command.
https://create-react-app.dev
MIT License
102.55k stars 26.79k forks source link

Allow default hostnames for fetch() in production #8346

Open getaaron opened 4 years ago

getaaron commented 4 years ago

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

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.

miraage commented 4 years ago

My 2 cents on the Proxy feature. It should only be used when you face issues with CORS in development. If there are no CORS issues, just use something like process.env.REACT_APP_API_URL for your API client.

getaaron commented 4 years ago

@miraage That's fair, there will always be CORS issues during development for a setup like this. But process.env.REACT_APP_API_URL could still point to the proxy server in development.

Would y'all be open to a pull request making this recommendation clearer in the docs?

miraage commented 4 years ago

@getaaron docs improvements are always welcomed. Try to contact docs maintainers https://github.com/facebook/create-react-app/blob/v3.3.0/.github/CODEOWNERS#L2

petetnt commented 4 years ago

Doc updates are always welcome! For what is worth, what @miraage suggests is our recommended approach. Note that you can have multiple .env files to archieve multiple URLs out of the box: https://create-react-app.dev/docs/adding-custom-environment-variables/#what-other-env-files-can-be-used