Greetings fellow beginner Rails/React dev’s! In this short tutorial, I will be retracing and sharing with you my process of deploying a web application that utilizes a React frontend coupled with a Rails backend. I deployed my backend on Heroku, and frontend on Netlify. Before we start, please ensure that your frontend and backend are stored in separate repos. All good? Let’s begin!
Deploying a React Frontend to Netlify
- In the script section of your
“react-scripts build && echo ‘/* /index.html 200’ > ./build/_redirects”. This script ensures that if you had chose to use something for routing (for example, React Router), the app will serve
index.htmlinstead of giving a 404 error, no matter what route you might be accessing the app from. To read more on this, please visit the Netlify documentation.
"start": "react-scripts start",
"build": "react-scripts build && echo '/* /index.html 200' > ./build/_redirects",
2. Create a Netlify account.
3. Under the Sites section, click “New site from Git”.
4. Select “Github”.
5. Select your project.
6. Select a branch of your project to deploy.
7. Set up environment variables to be available in Netlify. To do so, click “Site setting”, on the side bar, click “Build & deploy”, click “Environment”, then input variables according to what you have stored in your local
.env file. This could be various sensitive API keys, for example. Next, add key
CI and set the value to
false as one of the environment variables.
8. Go to “Deploys”, click “Trigger deploy”, and select “Clear cache and deploy site”.
Congratulations! You should now be able to access your frontend via the link Netlify has provided.
Deploying a Rails Backend to Heroku
This tutorial assumes that your database runs on PostgreSQL; if you have used SQLite3, which Heroku no longer supports, please follow steps in this Flatiron School’s tutorial.
- Create a Heroku account.
- Install Heroku CLI and login through your terminal by running
- Specify origins in
config.middleware.insert_before 0, Rack::Cors do
origins 'http://localhost:3000', '<URL of frontend/client app>'
resource '*', :headers => :any, :methods => [:get]
3. Commit your changes to Github.
4. In the terminal, run
heroku create <name of api>.
git push heroku <name-of-branch-to-be-deployed>:master.
6. Log into Heroku on the web, go to “Settings”, in “Config Vars”, add any local sensitive vars (API keys, for example).
7. In your terminal, run
heroku run rails db:create,
heroku run rails db:migrate,
heroku run rails db:seed. This creates the database, completes migration, and seeds your data on the Heroku server.
8. Lastly, go to your frontend code base, for requests made to the backend, ensure that you specify the URL to be your newly deployed API on Heroku. Follow step 8 in the previous section to re-deploy your app after this change.
And that’s it! Congratulations on the deployment of your full stack application!