Skip to content
Latchkey

How to Cache Build Dependencies in Azure Pipelines

The Cache@2 task restores a directory keyed on your lockfile hash, so unchanged dependencies are not reinstalled.

Add a Cache@2 step before install. Build the key from a lockfile hash so it busts only when dependencies change, and add restoreKeys for partial hits.

Cache the npm store

The key hashes package-lock.json; restoreKeys gives a fallback when the exact key misses.

azure-pipelines.yml
variables:
  npm_config_cache: $(Pipeline.Workspace)/.npm
steps:
  - task: Cache@2
    inputs:
      key: 'npm | "$(Agent.OS)" | package-lock.json'
      restoreKeys: 'npm | "$(Agent.OS)"'
      path: $(npm_config_cache)
  - script: npm ci

Gotchas

  • Point npm at a cache directory you control (npm_config_cache); caching node_modules directly is fragile across OSes.
  • The cache is saved only when the job succeeds and the key did not already exist.
  • Quote "$(Agent.OS)" in the key so Windows and Linux do not share an incompatible cache.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →