How to Cache the Build Output Between Jobs in GitHub Actions
Caching the compiled output keyed on a source hash lets downstream jobs restore it instead of building from scratch.
Cache the build directory with a key derived from the source files. The build job populates it once, and test or lint jobs restore it when the source is unchanged.
Steps
- Key the cache on
hashFilesof source plus the lockfile. - Build once, then restore the same key in dependent jobs.
- Use a job artifact instead when the consumer always needs the latest build.
Workflow
.github/workflows/ci.yml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: dist
key: build-${{ hashFiles('src/**', 'package-lock.json') }}
- run: npm ci && npm run buildGotchas
- If any consumer must always get the freshest build, use upload/download-artifact, not a cache.
- A cache key that omits a build input restores stale output; include every file that affects the build.
Related guides
How to Reuse a Build Artifact Instead of Rebuilding in GitHub ActionsBuild once and reuse the output across jobs in GitHub Actions by uploading it as an artifact and downloading…
How to Cache Docker Layers With Buildx in GitHub ActionsCut Docker build time in GitHub Actions by exporting and importing BuildKit layer cache through the GitHub Ac…