Andy Nguyen

How To Deploy Gatsby to GitHub Pages With gh-pages and GitHub Actions

This tutorial will show you how to use gh-pages and GitHub Actions to automatically deploy a Gatsby project to Github Pages repo. These steps and scripts are currently in use on this site.

Initial Context

This guide assumes there are two git repos, one to house the Gatsby project code and one for the Github Pages public files. Each git repo will have these characteristics:

Setting up GitHub Actions secret

In order to transfer files from one GitHub repo to another, the GitHub Actions need an authentication token to commit to the correct repo; this is achieved via personal access tokens. Follow these steps to setup a secret for the personal access token.

This secret will be used in both the deploy script and in the GitHub Actions workflow.

Installing npm packages

For the deploy script, two npm packages will be needed:

Setup Deployment

Now for the fun part! The next two scripts will work in tandem to deploy the Gatsby project to the Github Pages repo.

Making the deploy script

Add this npm script to the Gatsby project’s project.json.

"scripts": {
  ...
  "deploy": "gatsby build && gh-pages -d public -b main -r https://$PERSONAL_ACCESS_TOKEN@github.com/username/username.github.io.git"
}

Setting up the GitHub Actions workflow

Add this yaml file to the Gatsby project’s .github/workflows directory. This tutorial will name the yaml file deploy.yaml, resulting in .github/workflows/deploy.yaml.

name: Deploy site

on:
  push:
    branches: [ main ]

jobs:
  deploy-site:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout git branch
      uses: actions/checkout@v3.0.0
    - name: Setup Node.js
      uses: actions/setup-node@v3.0.0
      with:
        node-version: '16'
    - run: npm install
    - name: Deploy site
      run: |
        npm run deploy -- -m "deploy site via GitHub Actions" -u "github-actions-bot <support+actions@github.com>"
      env:
        PERSONAL_ACCESS_TOKEN: ${{ secrets.PERSONAL_ACCESS_TOKEN }}

Conclusion

That’s it! Any push to the Gatsby project GitHub repo will trigger an automatic build and deploy. Assuming username.github.io was the repo name and GitHub Pages was configured, there should be a live site at https://username.github.io!

Additional Resources