Skip to main content
In this guide, we’ll walk through how to automatically invalidate and recreate your build cache in Jenkins whenever package-lock.json changes. Leveraging the Job Cache Plugin’s cacheValidityDecidingFile option ensures that any update to your dependencies triggers a fresh cache, keeping your builds both fast and reliable.

Prerequisites

  • A Jenkins instance with the Job Cache Plugin installed
  • A Git repository named solar-system checked out on your Jenkins agent
  • Node.js and npm configured on the build agent

1. Install a New Dependency

First, switch to the solar-system repository on your local machine or CI checkout:
Then install the localtunnel package:
This updates both package.json and package-lock.json:
Changing or adding a dependency always modifies package-lock.json. We’ll use this file’s hash to decide cache validity.
Commit and push your changes to trigger the Jenkins pipeline:

2. Observe Cache Invalidation in Jenkins

Navigate to your Jenkins job’s Installing Dependencies stage for build #19, and search the logs for “cache”:
The image shows a Jenkins pipeline interface for a project in the "Gitea-Organization" with stages like "Installing Dependencies," "Dependency Scanning," "Unit Testing," and more. It includes details about the branch, commit, and specific tasks within the pipeline.

Build #19 Logs (Cache Miss)

Because package-lock.json changed, the Job Cache Plugin calculates a new hash, decides the existing cache is outdated, skips the restore, and then stashes all files to create a fresh cache.

Prior Build (Cache Hit)

Cache Invalidation Details

The image shows a console output from a Jenkins job, displaying logs related to caching and package installation processes. The word "cache" is highlighted multiple times throughout the text.

3. Cache Behavior Comparison

Conclusion

By configuring the Job Cache Plugin’s cacheValidityDecidingFile to point at package-lock.json, Jenkins automatically invalidates the cache whenever your dependencies change. This ensures that you always rebuild on the latest set of packages, while still benefiting from caching on subsequent runs.

Watch Video

Practice Lab