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

  1. Identify the dependency directory and lock file.
  2. Add actions/cache before the install step.
  3. 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-node built-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.