Skip to content
Latchkey

How to Cache Dependencies in Azure Pipelines

The Cache@2 task restores a saved package store keyed on your lockfile, so a clean install only runs when dependencies actually change.

Add a Cache@2 step before install. Set key to a hashed lockfile and path to the package store. On a hit the task restores it; on a miss it saves the path after the job succeeds.

Steps

  • Add Cache@2 before your install step.
  • Set key to a string that includes the OS and a lockfile hash.
  • Point path at the dependency store (for example the npm cache).
  • Add restoreKeys for a partial fallback when the exact key misses.

Pipeline

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

Gotchas

  • The cache is saved only when the job succeeds, so a failing job never seeds the cache.
  • Keys are immutable; change the key (not the contents) when you want a fresh cache.
  • Cache an install directory you can rebuild, not source you need fetched fresh.

Related guides

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