This article describes how to deploy a create-react-app to Netlify. It includes steps to connect the app to a Rails backend that is hosted on Heroku. You can follow Part 1 for one way to set up the Rails API with an Active Admin dashboard.
Step 6- Set up cors in Rails app so frontend can call backend
- In your Rails app, Add
gem 'rack-cors' to Gemfile.
Make sure tobundle install
it. - In
cors.rb
uncomment out the block and add in the origins for your development and production apps. The example is setup for an app that does not require any login by the frontend user. - Push these change to Heroku from the terminal command line:
git push heroku master
.
Step 7- Create-React-App (this guide will not go into the details of creating the React app)
1.To make the React frontend app, follow the directions in the official Create React App guide. Creat it in a separate directory from the rails app.
- Create a new repository on Github and connect your React app to it. *Note your backend and frontend apps will be in separate repositories.
- You can use various libraries to make API calls to your rails backend. Just check that the urls you use include both the current heroku app name/url and the correct name-spacing set up in your rails routes. Example:
https://dcpr.herokuapp.com/api/v1/teachers
nothttps://dcpr.herokuapp.com/teachers
if you put your controllers in the/api/v1
directory with corresponding routes.
Step 8- Deploy to Netlify
- Create a Netlify account.
- Find the button/option for “New Site from Git”.
- Make sure your current directory is your app’s root directory and then run in the terminal command line:
npm run build
. - At some point you will need to allow Netlify access to your Git repository. You can either allow it access to all your repositories or add them one at a time as you create sites.
- There will be a page that allows you to set your “Build Settings”. If you used create-react-app, set “Build Command” to
npm run build
and “Publish directory” tobuild/
. - Follow the Netlify docs to add a redirect rule if you used routing in your React app.
-
Change the site name. If you have a custom domain name or want to buy one from Netlify, go to “Domain Settings”. If you want a free name (will still contain ‘netlify’) but want to choose it, go to “Site Settings”, “Site Information” and click the “Change Site Name” button.
- Any changes pushed to the master branch of your git repository will be deployed. There are directions in the Netlify docs to change the branch if you prefer.