How do you cache dependencies in CI to speed up builds?

IntermediateConceptNode.js builds (npm, package.json)
Answer

Short answer

Save the package manager's download cache between pipeline runs, keyed on a hash of the lockfile, so dependencies are only downloaded again when the lockfile changes. Every CI system supports this.

What to cache per tool

Tool Cache path Key on
Maven ~/.m2/repository pom.xml (all of them)
Gradle ~/.gradle/caches, ~/.gradle/wrapper *.gradle*, gradle-wrapper.properties
npm ~/.npm package-lock.json
pip ~/.cache/pip requirements*.txt
NuGet ~/.nuget/packages **/*.csproj, packages.lock.json

Examples

# GitHub Actions — built into setup-* actions
- uses: actions/setup-node@v4
  with: { node-version: 22, cache: npm }
# GitLab CI
cache:
  key: { files: [package-lock.json] }
  paths: [.npm/]
script:
  - npm ci --cache .npm --prefer-offline

Note: cache ~/.npm (the download cache), not node_modules — npm ci deletes node_modules anyway.

Docker builds

Layer caching (copy the manifest/lockfile first) plus BuildKit cache mounts:

RUN --mount=type=cache,target=/root/.npm npm ci

What to say in the interview

"Cache the package manager's download directory keyed on the lockfile hash — ~/.m2, ~/.npm, ~/.cache/pip, ~/.nuget/packages — and for Docker builds use layer ordering and BuildKit cache mounts."

All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: Node.js apps: npm & package.json

More on Node.js builds (npm, package.json)