Heroku Deployment - React + Node

Heroku Deployment - React + Node

Recently I participated in a Hackathon and I had to deploy my app on Heroku. It was very difficult to find the correct steps to deploy, watched many tutorials but most of them were outdated but finally, I found the solution to it and I would like to share it with everyone.

The below steps are that I followed to deploy my app, if you have a better way of doing it do comment.

Test app

This is a test app that I created. It asks for the input and after the user submits the form it logs the input on the server-side.

React App

Screenshot 2021-11-08 120719.png

Screenshot 2021-11-08 122134.png

Server file

Screenshot 2021-11-08 120911.png

Screenshot 2021-11-08 122224.png

Deployment

Step 1:

We need to have the client folder (React App) with the server files it should look something like this -

Screenshot 2021-11-08 120140.png

Step 2:

Create a build version of your React App by doing npm run build in your client(React App)folder.

Screenshot 2021-11-08 124330.png

After making the build version, our React part is over.

Step 3:

Now, we need to tell Heroku to use the index file of the build version during production.

In the server file add the following code:-

if (process.env.NODE_ENV === 'production') {
    app.use(express.static('client/build'))
}

Screenshot 2021-11-08 124844.png

Step 4:

We need to keep our port dynamic because Heroku might give us some other port

Screenshot 2021-11-08 122517.png

Step 5:

we need to tell Heroku to run npm install & npm run build, and for that add the following in the scripts section of your package.json on the server side

"start": "node index.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client" # replace client with your React app folder name

Step 6:

For this step make sure you have "Hidden Items" enabled.

Delete the .git folder in the client folder.

Screenshot 2021-11-08 130557.png

Step 7:

make sure you are in the root directory,

  • Login into Heroku using heroku login
  • Create a Heroku App Screenshot 2021-11-08 135651.png

  • also make sure to add .gitignore in the server folder for folders like node_modules

  • then do the following in your root directory
    git init 
    heroku git:remote -a test-app-deploy-test # replace it with yours
    git add .
    git commit -am "message"
    git push heroku master:main
    
    if done correctly then you will get this message -

Screenshot 2021-11-08 155348.png

Click on the link to open your app.

Screenshot 2021-11-08 155437.png

if you see your node app, then you are almost done.

Step 8:

Remove this from your server file.

Screenshot 2021-11-08 155713.png

and then push the changes again like previously.

You will be able to see your React + node App deployed

Screenshot 2021-11-08 160124.png

  • if you are facing any issue
  • or you think this can be improved do comment :)