DEV Community

Play Button Pause Button
Brian Douglas for GitHub

Posted on • Updated on

Caching dependencies to speed up workflows in GitHub Actions

To make your workflows faster and more efficient, you can create and use caches for dependencies and other commonly reused files.

About caching workflow dependencies

GitHub Workflow runs often reuse the same downloaded dependencies from one run to another. For example, package and dependency management tools such as npm and Yarn keep a local cache of downloaded dependencies.

Jobs on GitHub-hosted runners start in a clean virtual environment and must download dependencies each time, causing increased network utilization, longer runtime, and increased cost. GitHub can cache dependencies you frequently use in workflows to help speed up the time it takes to recreate these files.

To cache dependencies for a job, you'll need to use GitHub's cache action. The action retrieves a cache identified by a unique key. For more information, see actions/cache.

GitHub logo actions / cache

Cache dependencies and build outputs in GitHub Actions

Example using the cache action

This example creates a new cache when the packages in the package-lock.json file change or when the runner's operating system changes. The cache key uses contexts and expressions to generate a key that includes the runner's operating system and a SHA-256 hash of the package-lock.json file.

name: Caching with npm

on: push

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2

    - name: Cache node modules
      uses: actions/cache@v2
      env:
        cache-name: cache-node-modules
      with:
        # npm cache files are stored in `~/.npm` on Linux/macOS
        path: ~/.npm
        key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
        restore-keys: |
          ${{ runner.os }}-build-${{ env.cache-name }}-
          ${{ runner.os }}-build-
          ${{ runner.os }}-

    - name: Install Dependencies
      run: npm install

    - name: Build
      run: npm build

    - name: Test
      run: npm test
Enter fullscreen mode Exit fullscreen mode

To learn more about cache hits and the cache eviction policy, check out the GitHub Documentation.

This is part of my 28 days of Actions series. To get notified of more GitHub Action tips, follow the GitHub organization right here on Dev. Learn how to build action with Node.js

Discussion (3)

Collapse
stevetaylor profile image
Steve Taylor

What's the point of this caching feature if I have to run npm install again anyway?

Collapse
juanmendes profile image
juanmendes

That's right. And beyond that, it should use npm ci, right? It's unclear what having npm install in your own steps means.

Collapse
estruyf profile image
Elio Struyf

Immediately implemented into the workflow I was creating! Great tip!