Hello Netlify enthusiasts! I’ve come across this difficulty with several Netlify apps in the past and am hoping to learn the best practice once and for all.
I commonly have to interact with a completely external backend service that I do no control in any way. My frontend infrastructure is typically a very normal create-react-app service that uses react-router.
In local development, I cannot hit this API directly:
fetch(https://externalservice.com/users/)
Because it will cause a CORS issue fetching from localhost:3000.
I solve this by putting a proxy in my package.json, a create-react-app feature:
{
"proxy": "https://externalservice.com"
}
At which point, relative frontend queries work expectedly, like:
fetch(/users)
During local development, my apps work perfectly now. However, when I got to deploy the app is where my problems begin. Of course, now the relative fetch requests do not work, because the proxy is only for local development.
I go to my netlify.toml file and add:
[[redirects]]
from = "/*"
to = "https://externalservice.com"
Which nearly works, except that now when my React-Router does not appear to work.
https://myapp.com/homepage
Will always return route not found. Searching online shows me that this is because you need something like this change to your YAML file in order to let client side routing take effect:
[[redirects]]
from = "/*"
to = "/index.html"
But I cannot make this change since the from
is the same.
Any and all help or guidance is greatly appreciated, thanks