How to cache dependencies in GitHub Actions?
· Category: DevOps & CI/CD
Short answer
Use actions/cache to save and restore dependency directories between workflow runs. This dramatically reduces install times for languages with heavy dependency trees.
Steps
- Identify the dependency directory and lock file.
- Add
actions/cachebefore the install step. - Use the lock file hash as the cache key.
Example
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '18'
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- run: npm ci
Tips
- Cache package manager global caches, not
node_modules. - Include the OS in the cache key.
- Use
actions/setup-nodebuilt-in caching for simplicity.
Common issues
- Cache size limits can cause evictions.
- Stale caches may contain outdated dependencies.
- Cache keys must be unique enough to avoid collisions.