I'm developing a web app that contains 2 projects, a Client project that uses React & react-router, and a Server project that Express. When I was developing locally, the Client was able to hit Server routes with code such as:
function handleLogout() {
fetch('/logout', {
method: 'DELETE',
headers: {
'Accept': 'application/json',
},
}).then(//etc)
and my package.json contained the line:
"proxy": "http://localhost:5000",
allowing it to easily hit my Server api for all routes.
However, I ran into problems deploying. I have never deployed a project this complex before, and don't know about the best practices. When I deployed (Server to Heroku and Client to Netlify, though I doubt that matters), the package.json proxy line didn't work even if I changed it to something like
"proxy": "https://my-server.herokuapp.com",
, so I found the solution of using a _redirects file in my public folder so that each time Netlify built my client, it would add a _redirects file that looks like:
/api/* https://my-server.herokuapp.com/:splat 200
/* /index.html 200
the 2nd line is to support react-router, to solve the problem documented here: StackOverflow: Netlify renders 404 on page refresh (using React and react-router)
the 1st line then is the only way I could figure out how to have my build hit API endpoints on the server. This means that I have to add /api before every route in my Client, such as:
function handleLogout() {
fetch('/api/logout', {
method: 'DELETE',
headers: {
'Accept': 'application/json',
},
}).then(//etc)
This solution is bad.
It means my Client build hits my Server build's api endpoints thanks to the 1st line added in _redirects, but now my local build has broken routes since every route is prefaced by the text /api, no longer matching my server routes, and the _redirects file doesn't do anything for local dev builds.
What is a more professional solution I can use, so that my production build sends API requests to https://my-server.herokuapp.com, but my local development build sends API requests to http://localhost:5000 ?