How to Build a Cache Key With hashFiles in GitHub Actions
hashFiles returns a single SHA over every file that matches the given glob patterns, ideal for a content-addressed cache key.
hashFiles('pattern', ...) computes one hash across all matching files. Put it in your cache key so the key only changes when a matched file changes, and unchanged dependencies keep hitting the cache.
Steps
- Pass one or more globs to
hashFiles(). - Combine the result with a stable prefix and
runner.os. - Match every file whose change should invalidate the cache.
Workflow
.github/workflows/ci.yml
- uses: actions/cache@v4
with:
path: ~/.npm
key: deps-${{ runner.os }}-${{ hashFiles('**/package-lock.json', '**/pnpm-lock.yaml') }}Gotchas
- hashFiles returns an empty string when nothing matches, which can produce a constant key.
- Patterns are relative to
GITHUB_WORKSPACE; a bad path silently matches nothing.
Related guides
How to Bust a Cache With a Version Prefix in GitHub ActionsInvalidate a poisoned or stale GitHub Actions cache by bumping a version segment in the key or a CACHE_VERSIO…
How to Set a Cache Key and restore-keys in GitHub ActionsConfigure actions/cache with an exact key and a restore-keys fallback list so a lockfile change still restore…