Skip to main content
In this lesson we show how to invalidate a Jenkins dependency cache automatically whenever project dependencies change — specifically when package-lock.json (or yarn.lock) is updated. This ensures fast builds when dependencies are unchanged, and safe cache refreshes when they are not.
A blue-to-teal gradient slide with subtle diamond shapes and centered white text that reads "Invalidate Caching." A small "© Copyright KodeKloud" appears in the bottom-left.
The Job Cacher plugin supports a cache-validity mechanism using a cache-validity deciding file (for example: package-lock.json). When that file changes, the plugin computes a new hash and decides whether an existing cache is still valid. Below is the Jenkins pipeline snippet used to cache node_modules and to make package-lock.json the cache-validity file.
Demonstration — add a dependency locally in the repository:
npm reports the new installation:
Installing the dependency updates both package.json and package-lock.json. When you commit and push these changes the pipeline triggers, and the Job Cacher plugin computes a hash of package-lock.json and compares it with the hash associated with the stored cache archive. Representative pipeline logs for the two outcomes:
  1. Cache is up-to-date and is restored:
  1. package-lock.json changed — cache is outdated and is recreated:
How it works (step-by-step)
  • The plugin computes a hash of the configured cache-validity file(s) (in this example: package-lock.json) in the current workspace.
  • It compares that hash with the hash associated with the existing cache for this job.
    • If the hashes match, the plugin restores the cache and the build step finishes quickly (for example: npm install reports “up to date”).
    • If the hashes differ, the plugin treats the cache as outdated, skips restoration, runs the install to produce up-to-date node_modules, then creates a new cache using the new hash.
  • Subsequent builds with the same package-lock.json content will restore the newly created cache until the lockfile changes again.
Quick reference table
Use cacheValidityDecidingFile (for example, package-lock.json or yarn.lock) so the Job Cacher invalidates dependency caches whenever the lockfile changes. This maintains build speed for unchanged dependencies while preventing stale or incompatible modules from being reused.
Links and references That’s all for now.

Watch Video

Practice Lab