Skip to content
Latchkey

How to Cache Dependencies in GitLab CI

GitLab CI caches directories declared under cache.paths, keyed by cache.key, with policy choosing pull, push, or both.

Add a cache: block with key, paths, and optionally policy. Use key.files to hash a lockfile so the cache changes with dependencies, and set policy: pull on jobs that only read the cache to avoid re-uploading it.

Steps

  • List the directories to cache under cache.paths.
  • Key on a lockfile with cache.key.files.
  • Set policy: pull on read-only consumers.

Pipeline

.gitlab-ci.yml
build:
  stage: build
  cache:
    key:
      files:
        - package-lock.json
    paths:
      - .npm/
    policy: pull-push
  script:
    - npm ci --cache .npm --prefer-offline

Gotchas

  • Cache is best-effort and tied to the runner or your object storage, unlike stricter artifacts.
  • Use policy: pull in test jobs so only the build job uploads the cache.

Related guides

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