How to Set a Cache Key and restore-keys in GitHub Actions
key is the exact match tried first; restore-keys is an ordered prefix list tried when the exact key misses.
A cache entry is stored under key. On the next run, actions/cache looks for that exact key; if it is absent it walks restore-keys top to bottom, restoring the newest entry whose key starts with the given prefix.
Steps
- Build
keyfrom a stable prefix plushashFiles()of your lockfile. - List one or more
restore-keysprefixes for partial hits. - Order restore-keys from most specific to least specific.
Workflow
.github/workflows/ci.yml
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
npm-${{ runner.os }}-
npm-Gotchas
- An exact key hit does NOT re-save the cache; only a miss followed by a new key saves.
- restore-keys only ever restores, so a partial hit still leaves the exact key empty until the next save.
Related guides
How to Use the cache-hit Output to Skip Work in GitHub ActionsRead the cache-hit output of actions/cache in GitHub Actions to conditionally skip a rebuild or reinstall ste…
How to Choose Between Caching node_modules and the Package Manager StoreDecide whether to cache node_modules or the npm, yarn, or pnpm download store in GitHub Actions, and why cach…