Deploying Your React App to Heroku

How to Successfully Deploy Your Production Build create-react-app to Heroku

Image for post
Image for post

So you’ve spent hours building your React app and finally have something you’re proud of and are ready to share — now what?

The next step is to deploy your app to a cloud application platform that allows you to run, manage, and scale your applications. Heroku is one such platform that is popular thanks to its ease of use and efficiency. However, there is a slight gotcha when it comes to deploying a production build of a React app built using create-react-app to Heroku — you will first have to run through a few additional steps to configure your application to be able to work correctly with Heroku.

Firstly, you will want to make sure you have run npm run build in order to create a production build of your app. This will create a “build” directory in your application. This is what you want Heroku to be serving, but you’ll have to let Heroku know that — right now, it is looking to serve your files from the “src” directory, which is what you’ve been working on in the development phase. Additionally, the application does not currently have a server for production deployment, so we’ll have to take care of that as well.

Image for post
Image for post
Credit: Geeks for Geeks

You can solve the problem of defining a server for production deployment by setting up an Express server within your project. Whilst in your root directory, run the following command:. You can take a look at the documentation for Express to understand how Express works. Next, you’ll need to create a “server.js” file within the root directory. In this file, you will initiate the Express server (using the express() function), set up a variable listening port (I’ve chosen port 5000, but you can use whatever one you desire), specify the “build” directory as the one for the app to use, and direct all server requests to “build/index.html”. Here is how my “server.js” file looks:

Almost there!

Now you have to let Heroku know to use this Express server that you’ve just set up. You can do this by creating a procfile that “specifies the commands that are executed by the app on startup” (Heroku documentation). You will create this file in the root directory. It is important to note that this file needs to be named procfile without any extension specified. Within this file, you need to include — this tells Heroku to use node to run the “server.js” file.

Now your app should be ready to be deployed to Heroku!

Source

Fullstack Software Engineer based in NYC. Passionate about creating social change and making a difference through innovative, powerful technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store