Script Valley
CI/CD with GitHub Actions
Building a CI PipelineLesson 2.2

How to cache dependencies in GitHub Actions to speed up builds

actions/cache, cache key, cache restore, npm cache, pip cache, cache hit vs miss, dependency caching strategy

Why Caching Matters

Cache hit vs cache miss comparison

Installing dependencies is the slowest step in most CI pipelines. npm install or pip install can take 1–3 minutes per run. Caching stores the installed packages between runs so a cache hit skips the installation entirely.

Caching Node Modules

- uses: actions/cache@v4
  with:
    path: ~/.npm
    key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
    restore-keys: |
      ${{ runner.os }}-npm-

path — the directory to cache. For npm this is the global cache (~/.npm), not node_modules. key — a string that identifies the cache. Including hashFiles('**/package-lock.json') means the cache is invalidated automatically when package-lock.json changes. restore-keys — fallback keys used for partial cache hits when the exact key misses.

Alternatively, actions/setup-node has a built-in cache: 'npm' input that handles this automatically:

- uses: actions/setup-node@v4
  with:
    node-version: '20'
    cache: 'npm'

Use the built-in cache option when available — it is simpler and less error-prone than managing cache keys manually.

Up next

How to use environment variables and secrets in GitHub Actions

Sign in to track progress