Deploy Gatsby Site to GitHub Pages using GitHub Actions

We are seeing an increase in the popularity of JAMStack. Gatsby is one of the popular JAMStack frameworks.

There are a lot of tools and services available to host a static site build by Gatsby. GitHub Pages, a free static site hosting service by GitHub, is one of them.

In this article, we will see how to build and deploy your existing Gatsby site using GitHub Actions on every push to GitHub repo where your site is stored.

        {
          "scripts": {
            "build": "gatsby build"
          }
        }

GitHub Add a new secret form

        name: Gatsby Build and Deploy to GitHub Pages on Push
        
        on:
          push:
            branches:
              - master
        
        jobs:
          build-and-deploy:
            runs-on: ubuntu-latest
            steps:
              - name: Checkout
                uses: actions/checkout@master
        
              - name: Build and Deploy
                uses: JamesIves/github-pages-deploy-action@master
                env:
                  ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}
                  BRANCH: gh-pages
                  FOLDER: public
                  BUILD_SCRIPT: yarn && yarn run build

This GitHub action will trigger if any push happened to master, spawns a ubuntu instance and check out the repo. Then it will do yarn and yarn build, which will generate the output to public directory. The contents of the public folder will be deployed to gh-pages branch.

Now on every push to your repo will build your site and deploy it to GitHub pages.

I hope this helped you to set up the deployment of Gatsby site to GitHub Pages using GitHub actions. Feel free to ask anything around this in the comments section below.