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
Server file
Deployment
Step 1:
We need to have the client folder (React App) with the server files it should look something like this -
Step 2:
Create a build version of your React App by doing npm run build
in your client(React App)folder.
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'))
}
Step 4:
We need to keep our port dynamic because Heroku might give us some other port
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.
- For the next steps make sure you have the Heroku CLI installed.
- Download: devcenter.heroku.com/articles/heroku-cli
Step 7:
make sure you are in the root directory,
- Login into Heroku using
heroku login
Create a Heroku App
also make sure to add .gitignore in the server folder for folders like node_modules
- then do the following in your root directory
if done correctly then you will get this message -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
Click on the link to open your app.
if you see your node app, then you are almost done.
Step 8:
Remove this from your server file.
and then push the changes again like previously.
You will be able to see your React + node App deployed
- if you are facing any issue
- or you think this can be improved do comment :)