Deploying a Rails / React App to Heroku
Tags: rails, react, ruby, javascript
Published: 2020-09-29 17:18:58

In my last post, I went walked through how to deploy a Rails application on Heroku. If you would like to view that walkthrough, you may view it [here](). This time, we're going to deploy a full stack application with a frontend using React and a backend using Rails. I am assuming you are decently familiar with both the React and Ruby on Rails frameworks, so I will not be going into detail about the application creation itself. So without further ado, let's get started!

## Heroku CLI Setup

To use Heroku, we need to install the Heroku CLI. To do this, use the installation instructions provided [here](https://devcenter.heroku.com/articles/heroku-cli#download-and-install). If you're on Mac, the easiest method to installing the Heroku CLI is through Homebrew. If you do not have Homebrew installed on your machine, use the following terminal command to install it.

```
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
```

Once installed, you can use the brew installation method shown in the Heroku installation instructions.

Quick note: Since I have not used Windows to instantiate Heroku Rails apps, I will not provide instructions on using the Heroku CLI in Windows.

## Setting up Rails Application

Since we are going to have a frontend server for our application, we need to configure Rails to be used as an API. To do this, we can use the "--api" flag when creating our Rails project.

Also, since Heroku does not support SQLite3, we must use an alternative database structure. For this tutorial we are going to use Postgres. To tell Rails to use Postgres, we can use the "--database=postgresql" flag.

I'm going to call this project superheroku-api. All in all, our terminal command to create a new Rails application as an API using Postgres is:

```
rails new superheroku-api --api --database=postgresql
```

*Note:* It will make your life a lot easier if you have separate repositories for both your frontend and backend projects.

Go about creating your rails application as an API. I will not go into detail about doing so since this tutorial concerns mainly Heroku deployment. However, if you need a sample project, you may use the one located [here](https://github.com/brandonbrown4792/superheroku-api).

*Quick Note:* Make sure you enable CORS by enabling the rack-cors gem in the Gemfile, uncommenting the code in config/initializers/cors.rb, and setting 'origins' to '*'.

## Heroku Deployment for Rails App

Once you've got your app ready, we can now deploy to Heroku. First, navigate to the root of your Rails project in your terminal.

If you have not done so already, be sure to create an account with Heroku. You may do so [here](https://signup.heroku.com/).

Now that that's done, we need to log into Heroku on the CLI. Make sure you're in the root directory of your Rails app and run the following in your terminal:

```
heroku login
```

This should prompt you to press any key to open up a browser to login. Follow the login instructions, and you should be greeted with a login success message in the terminal.

![Heroku Login](https://dev-to-uploads.s3.amazonaws.com/i/e4eik7wvr15zqoogrcgk.png)

Now we must create our Heroku app. To do this run:

```
heroku create [APP_NAME]
```

"APP_NAME" is whatever you would like your app to be called. After your app is created, you will be able to access it by going to [APP_NAME].herokuapp.com, so make sure to name your app something that makes sense. Alternatively, you can leave the app name blank and Heroku will assign you a random app name.

![Create Rails Heroku App](https://dev-to-uploads.s3.amazonaws.com/i/h0tf5eafbc3y0pdrti04.png)

Next, we need to push our master branch to Heroku. To do this, run:

```
git push heroku master
```

This could take some time as Heroku is setting up your Rails application on its server system. This includes all gem requirements that you have in your gem file as well as some overhead installations. After everything finishes, you should see something similar to:

![Deployed Rails App](https://dev-to-uploads.s3.amazonaws.com/i/f05wnsixqn45oj8up1wt.png)

Hurray! We have officially deployed our app to Heroku. However, out of the gate, your app will not be working correctly. This is because we have to migrate the database and seed it. To do this, first run:

```
heroku run rails db:migrate
```

then run:

```
heroku run rails db:seed
```

For each of these commands, Heroku will display the response similarly to how Rails does when running database commands locally in your terminal. Therefore, all of the response messages (commits, migrations, etc.) should be fairly familiar to you.

Quick note: "heroku run" allows you to run terminal commands very similar to running them on your local machine. "heroku run" can be very powerful, but be careful when using this as you are running scripts on your Heroku instance.

## Testing Rails Application

Now we must test our API endpoints. If you used the supplied Rails application, then the endpoint we need to test is https://APP-NAME.herokuapp.com/superheroes where APP-NAME should be replaced by your Heroku deployed application name. If you are greeted with JSON, you are good to go to the next step.

## Setting Up React Application

To create a React application, you may use the yarn create react-app command. For this project, I'm going to call the application superheroku-front. If you would like, you may use the React application I have created [here](https://github.com/brandonbrown4792/superheroku-front).

```
yarn create react-app superheroku-front
```

Go through and create your React application as you typically would with all features and functionality. The only change we need to implement is to point our endpoints to our newly created Rails Heroku application.

To make things easier on yourself, it would be very helpful to create a global identifier for your endpoint. The objective of this global identifier is tell your React application to use localhost:3000 in development and to use your Heroku Rails API URL in production. To do this, you can define a new file called apiRoot.js that contains the following code:

```javascript
const DEV_URL = 'http://localhost:3000/';
const PROD_URL = 'https://[APP-NAME].herokuapp.com/';
export const API_ROOT = process.env.NODE_ENV === 'development' ? DEV_URL : PROD_URL;
```

This bit of code will look at the process.env.NODE_ENV (will be development, production, etc.) and assign the appropriate URL to the API_ROOT variable. Pretty neat, huh?

Replace APP-NAME with your Heroku Rails application name. Now, if you import API_ROOT from your apiRoot.js file, you can use this new API_ROOT variable as the root for all your fetches. For example...

```javascript
fetch('http://localhost:3000/superheroes')
  .then(response => response.json())
  .then(superheroes => ...);
```

becomes...

```javascript
fetch($`{API_ROOT}/superheroes`)
  .then(response => response.json())
  .then(superheroes => ...);
```

Since we are using this dynamic API_ROOT, we do not have to change anything in the application when we need to retrieve data from localhost:3000 or our Heroku Rails application.

## Heroku Deployment for React App

Now that you've got your React application working, we are now ready to deploy to Heroku. The only difference between deploying a Rails application and React application to Heroku is the inclusion of the correct buildpack option. Create the React Heroku application similarly to how we created the Rails one but including this buildpack option.

```
heroku create APP-NAME --buildpack mars/create-react-app
```

Once created, you should get something similar to the following:

![Heroku Create React App](https://dev-to-uploads.s3.amazonaws.com/i/7acy0ytj58vgj343cjpk.png)

Next, we must push our code to Heroku with:

```
git push heroku master
```

This will take a while since React takes a little longer to build than Rails. After it finishes, you should see dialog similar to the following:

![Heroku React Deployment](https://dev-to-uploads.s3.amazonaws.com/i/2jmu5su2arqm2vsn3tmq.png)

After this completes, you should be able to go to your React Heroku URL and see all your hard work hosted on the internet! Test your React application, and if you are able to pull in data from the backend, you have done everything correctly. You now have a web application with a frontend server that talks to a backend server all hosted on Heroku!

## A Quick Note on Free Heroku

Heroku is a wonderful tool to quickly and easily get your applications running; however, there are some drawbacks with this service. The main drawback comes with Heroku's free tier instances (called Dynos) falling asleep after 30 minutes of no use. Because of this, connecting to your Heroku app may initially take 15 seconds or so. Heroku does offer a solution to this; however, it is by joining a paid tier plan.

If you really need your Heroku app to be live 24/7 but still do not want to pay, there is an app called Kaffeine that will wake your application for you every 30 minutes or so. You may find that app [here](http://kaffeine.herokuapp.com/). 

**Be careful when doing this.** While this sounds great, Heroku only gives you a set pool of free hours per month that all your Dynos may use. After you use your hours, you Dynos are put to sleep until the next month. Only use the Kaffeine service if you have one app, or if you only wish to keep it awake for a particular amount of time.

## Conclusion

I hope this post has inspired you to start deploying your Rails / React applications. Once you get the hang of it, the process is fairly straight forward and easy to do. I hope you now have the confidence and expertise to start deploying your super awesome Rails / React applications.