How to cache GatsbyJS .cache and public folders between builds using GitHub Actions

Viewed 562

I am trying to persist cached data between our GatsbyJS builds using GitHub Actions utilizing the actions/cache task.

name: Gatsby Contentful Build

on:
  push:
    branches: [master]
  pull_request:
    branches: [master]

jobs:
  build_job:
    runs-on: self-hosted
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v1.1.0
      - uses: bahmutov/npm-install@v1.1.0
      - name: Cache
        uses: actions/cache@v1.1.2
        with:
          path: .cache
          key: cache-folder-key
      - name: Cache public folder
        uses: actions/cache@v1.1.2
        with:
          path: public
          key: public-folder-key
      - run: cd plugins/gatsby-source-contentful && yarn build
      - run: yarn build

On initial build the caches are not found, then gatsby creates .cache and public from scratch, builds and saves the two folders to the action cache.

On the second build new cache is found and gatsby builds successfully but then cache is not not updated.

It seems like I am struggling to understand how to bust the cache using the key name.

This is the way I understand it should work, please correct me if I am wrong.

enter image description here

2 Answers

Cache will not automatically update if cache is hit. Your primary cache key must contain file hashes that is unique to a new build. If your Gatsby build needs to call some remote API to get the data, then you cannot use the official cache action.

You can try this fork that always saves cache: https://github.com/marketplace/actions/always-cache

But use it at your own risk.

better use some identifier for restore keys if you want to save cache because you have given a very generic name for restore keys. you can use environment variables like GITHUB_RUN_ID / GIHUB_COMMIT_SHA appending to hard-code restore keys

Related