Nathan Smith
  • Projects
  • About
  • Contact

Publishing a Dev and Production CRA App to GH Pages

May 20, 2020, 5:57 PMReact

GitHub Pages is a free static site hosting service from GitHub that allows you to freely publish a static site with a custom domain. What if you want to publish two different versions of your create-react-app React application (like a dev version and production version) with two different custom domains? Through a little hack, this is pretty easy to set up.

1. Create two repos

You'll need two repos:

  1. Your master repo, this will contain only your production site
  2. Your dev repo, this will contain your development branch as well as your dev site

2. Enable GitHub Pages on both repos

Select the master branch as the branch to use on both repos. GitHub should pick up the domain from the CNAME files.

3. Add two CNAMEs

In your source, add a CNAME file to the public folder with your dev domain. For example:


Now add another CNAME file for your production environment. I've named this ProdCNAME:


4. Setup gh-pages and publishing

In your CRA, install gh-pages:

npm install --save-dev gh-pages

Now, we need to enable publishing by adding new scripts and attributes to our package.json:

"scripts": {
  "predeploy": "npm run build",
  "deploy": "gh-pages -d build -b master",
  "swap-cname": "rm ./build/CNAME && mv ./build/ProdCNAME ./build/CNAME",
  "preproduction": "npm run build && npm run swap-cname",
  "production": "gh-pages -d build -b master -r"

There are a few things happening here:

  1. The predeploy and deploy scripts are just copied from the create-react-app documentation.
  2. The swap-cname script removes CNAME and renames ProdCNAME to CNAME for the production deployment.
  3. The production script pushes the code to a different repo.

5. Deploy to dev and prod

All that's left is to deploy to each environment:

// for dev
npm run deploy

// for prod
npm run production

For a full example you can check the repo for this site.

Previous: Why functional components are the future of React (but hooks are dangerous)

Next: usePrismjs: A prismjs hook for CRA & React