Deploy full stack React app on Heroku

Thi Nguyen - Mar 7 '23 - - Dev Community

We're gonna deploy our full stack React app in the same Heroku app. The back end is a Node express app, while the front end is a react app. The outcome of the deployment is that our backend would live on https://react-app-name.herokuapp.com/api and our client can be accessed by public via https://react-app-name.herokuapp.com. I have my Postgresql database set up on a unbuntu server. Click here if you would like to learn more.

This is the structure of my app

app
|_server
|__client
Enter fullscreen mode Exit fullscreen mode

1. Create a Heroku account

Sign up for a Heroku account. You need to add a credit card in order to create an app but it's not gonna cost anything to deploy the app. There's used to be a free tier plan that we can use to add Postgresql db service which made everything so much simpler, however they scrapped that, hence I chose to host the db on a virtual machine.

Click New -> Create New App and choose a name for it.

2. Add the config vars

In the Settings section of the app on heroku, add the env variables needed to run your app.

In my case, since I have the db hosted on an aws ec2 instance, I have the following variables

REACT_APP_BASE_URL=/api
PG_USER=ubuntu
PG_PASSWORD=password
PG_HOST=dbhost
PG_PORT=5432
PG_DATABASE=dbname
PG_DIALECT=postgres
Enter fullscreen mode Exit fullscreen mode

3. Configure the Node server app

Add a Procfile file at the root of our project which is where the package.json for the server app lives. The reason I have to make a distinction is because I have my server folder nested in a parent folder that doesn't have a package.json. Procfile will tell heroku how to run the app when it's deployed to heroku. node server.js is how the server app is launched. If the main point of entry of your program is called differently, change the script to node point-of-entry.js

In the Procfile, add the following

web: node server.js
Enter fullscreen mode Exit fullscreen mode

4. Deploy the app

I assumed that you already have git initialized on your project otherwise run git init

After committing all the code to your gh repo, run heroku git:remote -a heroku-app-name. Replace heroku-app-name with the name of your heroku app.

Like mentioned above, I have my backend directory in another directory, hence I have to adjust the command to deploy the code to the remote heroku.

git subtree push --prefix server-folder heroku main
Enter fullscreen mode Exit fullscreen mode

If your app doesn't have the same structure, you can just run the below and it should be good.

git push heroku main
Enter fullscreen mode Exit fullscreen mode

It's gonna take a while to deploy your app. Inspect the logs on heroku if you encounter any issue.

If everything is done correctly, you should have a live app.

. . . . .