Deploy CRA to GitHub Pages and Netlify


Let’s say you want to deploy a Create React App (CRA) to GitHub Pages and Netlify.

If your GitHub Page is a project site, then the site will be deployed to a subfolder:

https://<username>.github.io/<project>/

But on Netlify, the site will be deployed to the root:

https://<project>.netlify.app/

Initially, I thought I needed to add a redirect or rewrite rule on Netlify.

But it turns out the solution is simpler than expected.

Instead of storing the site URL in package.json "homepage", I was able to store it in the environment variable PUBLIC_URL.

So delete "homepage" from package.json:

-"homepage": "https://username.github.io/project/",

And set PUBLIC_URL in .env:

+PUBLIC_URL=/project/

Both steps can be done by running the commands:

sed -i '' '/"homepage"/d' package.json
echo PUBLIC_URL=/project/ >> .env

Now when you build for GitHub Pages, everything should still work as expected.

When you build for Netlify, you’ll need to set the environment variable PUBLIC_URL to "" for it to work.

See textventure/play, which is deployed to GitHub Pages and Netlify.



If you enjoyed this post, please consider supporting this site!