Skip to main content
In this guide, we’ll explore how GitHub Actions invalidates and rebuilds the NPM cache when your project’s dependencies change. You’ll learn how cache keys work, how to trigger a cache rebuild, and how to verify the new cache in your repository.

Background

GitHub Actions uses cache keys to store and restore dependencies. By hashing package-lock.json, we ensure that any update to dependencies generates a new cache key, invalidating the old cache automatically. Key points:
  • We cache node_modules using the hash of package-lock.json.
  • Changing dependencies updates the lock file, resulting in a new cache key.
  • A new cache is created when the key doesn’t match any existing cache.

Local Setup

First, clone the repository and switch to the feature branch:
Open package.json to review current dependencies:

Adding a New Dependency

Let’s simulate a dependency change by installing nodemon:
Your package.json will now include:
Commit and push the changes:

Workflow Cache Configuration

Our GitHub Actions workflow uses the official actions/cache action to save and restore node_modules:
When you push a change to package-lock.json, the hashFiles function produces a new key, and the workflow cannot find an existing cache that matches it.

Observing the Workflow

After pushing your commit, the workflow runs again. In the Unit Testing job, open the Cache NPM dependencies step:
The image shows a GitHub Actions workflow page for a repository named "solar-system," displaying the progress of unit testing and code coverage jobs. The workflow is currently in progress with some jobs completed.
You’ll see:
No cache was found
The image shows a GitHub Actions workflow interface for a project named "solar-system," displaying the status of unit testing jobs on different environments, with a focus on caching NPM dependencies.
The runner installs dependencies afresh and then uploads the new cache. Since parallel jobs may try to save the same cache simultaneously:
If multiple jobs use the same cache key, one job will succeed in saving while the others may report a save failure. This is expected behavior.
Finally, verify the new cache in your repository’s Caches section:
The image shows a GitHub Actions interface displaying cache details for a project, including cache keys, sizes, and last used times.

Summary

  • GitHub Actions invalidates caches when the cache key changes.
  • Hashing package-lock.json ensures dependencies are up to date.
  • You can confirm the cache status in the workflow logs and the Caches tab.

Watch Video