I have been trying to build a Rails API with an integrated React front end and deploy it to Heroku. I am using create-react-app to build the React app in a directory called "client" within the Rails project folder. I run the Rails api on localhost:3001 and the React app on localhost:3000. And it works when I deploy it to Heroku except when I am using a React Router url and try to refresh the page, or if I try to copy and paste the URL in the browser. It's the same result on multiple browsers. For example if I go to the root url: https://appname.herokuapp.com it will display the React app with a navbar. If I click on "articles" it will take me to https://appname.herokuapp.com/articles and display the react articles page. However if I refresh the browser I just get an empty page. Same if I copy/paste this url in a browser.
I have followed three separate tutorials on deploying a Rails/React app to Heroku all from around 2018. They all mention this issue and offer the exact same solution.
In app/controllers/application_controller.rb add this action:
def fallback_index_html
render :file => 'public/index.html'
end
And in the routes add this route at the bottom:
# config/routes.rb
get '*path', to: "application#fallback_index_html", constraints: ->(request) do
!request.xhr? && request.format.html?
end
They all say this will work. But after trying three separate tutorials that all fail on the same issue I am at a loss. I know that on the page refresh the app is looking for the Rails routes not the React Router routes. The above solution is not working. Maybe something changed with Heroku, Rails or React that is preventing this from working now. How do I fix this?