How to deploy a create-react-app with github-actions

Here’s a quick guide on how to deploy a CRA (create-react-app) to GitHub pages using GitHub actions. We’ll create a GitHub Action workflow that runs the build command and then deploys the build directory by pushing it to the gh-pages branch.


1. Prefix URLs

GitHub pages urls looks like, so we need to make sure all our relative URLs are prefixed by /repo-name. Using create-react-app, it's enough to add "homepage": "/repo-name", to the package.json. The build command will automatically take care of the rest.

2. Add deployment key

Deploying to GitHub pages means pushing the build directory to the gh-pages branch. Currently, pushes using default GitHub Actions credentials do not trigger a GitHub pages rebuild. Meaning, we need to set up a deployment key for the repo first that can be used by the GitHub action. I use the same deployment key for the gh-pages deployment actions across all my repos. You can create a new SSH public/private key pair using this command:

  1. Following the Getting Started section of this gh-pages Action we add a new write-access deployment key** in the /repo/settings/keys section pasting our public key from the .pub file.
  1. We need to make the private key accessible to our GitHub action. To do this add the corresponding secret key in the repo/settings/secrets section. Make sure to name it ACTIONS_DEPLOY_KEY.

GitHub Action

Now all that’s left is to create a new .github/workflows/deploy.yml workflow file and paste the following GitHub action YAML code:

On each push to the master branch it performs the following tasks:

  1. Checkout the code from the master push
  2. Install Node v12
  3. Run npm install
  4. Run npm build which creates the build folder.
  5. Deploy the ./build folder to gh-pages using the deploy key in the secrets.ACTIONS_DEPLOY_KEY variable.

To test the deployment process push this workflow file to master.

Written by

Full Stack Software Engineer #javascript #EOS. Into Recreational Math / CS 🤯 Just message me about anything, my mind is open.

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