How to have a “cache per package.json” file in GitLab CI?

I have a Vue web application that is built, tested and deployed using GitLab CI.

GitLab CI has a “Cache” feature where specific products of a Job can be cached so that future runs of the Job in the same Pipeline can be avoided and the cached products be used instead.

I’d like to improve my workflow’s performance by caching the node_modules directory so it can be shared across Pipelines.

GitLab Docs suggests using ${CI_COMMIT_REF_SLUG} as the cache key to achieve this. However, this means “caching per-branch” and I would like to improve on that.

I would like to have a cache “per package.json”. That is, only if there is a change in the contents of package.json will the cache key change and npm install will be run.

I was thinking of using a hash of the contents of the package.json file as the cache key. Is this possible with GitLab CI? If so, how?

PS - This is a crosspost from so feel free to also answer there and I’ll accept the best answer. Many thanks!