Hauling your Hard Made React Application to Production Together with Backend

Hauling your Hard Made React Application to Production Together with Backend

How to deploy a react app in production while linking the backend with React

I have gone through many tutorials that suggest making a proxy in the package.json and connect the frontend and backend of your application. But this wont won’t work when you are going for production because you obviously won’t be using localhost there.

So how do we deploy a app that is fuly built(frontend and backend) but which was running on a localhost up until now and is finally production ready. GOOD QUESTION!! Be glad you ended up here as I am going to show you exactly that. But beware that I am using you have used create-react-app initially as the commands are related to it( I will make a different article for babel).

First, go to your react project and run the command

npm run build

This will make an optimised build out of your react app and also make the static assets out of it. Next, move that build into your server.

The file directory should look something like this

I am using express and in it to serve up static files, we use the command

app.use(express.static(path.join(__dirname, 'build')));

Copy paste this command into your app.js.
Now the final step is to serve the index.html file from the bundle when the initial request comes.

app.get(‘/’, (req, res) => {
res.send(“index”);
});

That is it, now you are done. Its ready to be deployed to anywhere(just the server part is enough).
If you particularly want to deploy it to heroku and you also want to automate the running of the build command, then store the whole react app in a client folder and in the scripts of the package.json of the server type in the following script

"heroku-postbuild": "cd client && npm install && npm run build"

Now, you just have to git push to heroku and it will take care of building the react app and everything but now as we changed the folder structure of the project in the app.js of the server, change the following line of code

app.use(express.static(path.join(__dirname, 'client/build')));

Don't forget to join the emailing list for more such awesome content