deploying frontend (react) and backend (express/node)
I'm finally here! I've deployed the app.
It's been a journey to get here, and glad that I can finally understand ins and outs of the deployment. Gones are the days where I would just blindly follow the tutorials, now I feel like I'm understanding each bits quite well.
Some key understandings I needed were:
- git remote -v
- git remote add heroku https:....git
- git push heroku main
- cp -r, rm -r, bash paths
- heroku logs
- heroku create
- what scripts in package.json do, and Procfile that runs start script
- node index.js
- npm run start
I was deploying it today, but I did get some places where I would not know what went wrong. Let's go through it one by one:
Recommended: make sure that you try heroku create again then push to heroku
Just to make sure that the problem you are having is not to do with some previous git repository setting
1. PORT did not bind
First thing you should do is to check logs by 'heroku logs'.
It says there was some issue with the port. This is because we are running express at port 3001 (in local host), but we can't arbitrarily set it like that in heroku. You should use process.env.PORT which is a port number allocated by heroku:
2. Frontend axios baseurl
Your axios will now reference the /api/notes from the same host at the same port. So make sure to build this then put it into the build folder of backend.
Steps to deployment
I can't be bothered reproducing every step, but here's the idea:
Here, I'm showing the project for backend. Basically, index.js that runs with node index.js. Not the create-react-app. This is the one that will be deployed to the internet, not the front end project.
Then where's the create-react-app project? It's compiled and placed in the build folder as 'static' html,css,js files.
You do:
npm run build
in the front end app to get the build folder, then
cp -r <that build folder> <directory of backend project>
Then you do
app.use(express.static('build')) like what's shown above.
This means that whenever express gets the GET request, it will see if that route is implemented in the project and return the page for it. In our case, request to '/' will return the 'static' html,css,js files and display the frontend.