🎓 A1Learner
🔍
0 of 50 lessons completed

GitHub Actions: Caching Dependencies

Caching saves downloaded files between runs. A cached run skips the download and starts work sooner.

The built-in npm cache

This setup step turns on the built-in npm cache.

- uses: actions/setup-node@v7
  with:
    node-version: '24'
    cache: 'npm'

The cache action

This step saves the npm cache folder by a key.

- uses: actions/cache@v6
  with:
    path: ~/.npm
    key: npm-${{ hashFiles('package-lock.json') }}

The key names the cache

hashFiles reads a file and makes a short fingerprint of it. A changed lock file gives a new key.

key: npm-${{ hashFiles('package-lock.json') }}

Example

name: Cache demo

on: push

jobs:
  cached:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: '24'
          cache: 'npm'
      - run: npm test

Key points

  • A cache is a saved copy of files from an earlier run.
  • actions/cache saves and restores a folder by a key.
  • The key names the cache, often from a lock file.
  • setup-node has a built-in cache option for npm.
  • The first run fills the cache. Later runs restore it.
  • A cache miss still runs fine. The step just downloads again.
  • The demo repo has no dependencies, so the npm cache has little to save.
  • The real win shows on a repo with dependencies.
  • Times in this lesson are expected. Real times vary by run.
  • Caching trades a small save step for a faster run next time.

In this example, the workflow runs on every push. Checkout downloads the repo. Setup-node installs Node 24 with the built-in npm cache turned on. The first run finds no cache, so it downloads and saves one. The second run restores the cache instead. Both runs pass the tests. The demo repo has no dependencies, so the saving here is small. A repo with many dependencies would save far more.

Note

A cache never changes what the tests check. It only skips repeated downloads.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What happens on a cache miss?