GitHub Actions caching dependencies
Author: Nicolás de la TorreDo you know about the importance of GitHub Actions Caching Dependencies? When running workflows on GitHub Actions, installing dependencies can be a time-consuming step. These Actions are also billed based on execution time, so optimizing them helps save money, which is crucial.Plan | Storage | Minutes (per month) |
GitHub Free | 500 MB | 2,000 |
GitHub Pro | 1 GB | 3,000 |
GitHub Free for organizations | 500 MB | 2,000 |
GitHub Team | 2 GB | 3,000 |
GitHub Enterprise Cloud | 50 GB | 50,000 |
Caching node_modules in GitHub Actions
Let's take the following GitHub Actions workflow as an example:name:Testson:[push,pull_request] jobs:install:name:Installpackagesruns-on:ubuntu-latesttimeout-minutes:20outputs:test-files:${{steps.list-tests.outputs.test-files}}steps:-name:Checkoutrepositoryuses:actions/checkout@v3-name:SetupNode.jsuses:actions/setup-node@v3with:node-version:'18'-name:Cachenode_modulesid:cache-node-modulesuses:actions/cache@v3with:path:node_moduleskey:node-modules-${{hashFiles('yarn.lock')}}-name:Installdependenciesrun:yarninstall-name:Listtestfilesid:list-testsrun:|nodescripts/list-tests.jsecho"test-files=$(cattest-files.json)">>"$GITHUB_OUTPUT" tests:name:Runtestfile:${{matrix.file}}runs-on:ubuntu-latesttimeout-minutes:20needs:[install]strategy:matrix:file:${{fromJson(needs.install.outputs.test-files)}}steps:-name:Checkoutrepositoryuses:actions/checkout@v3-name:SetupNode.jsuses:actions/setup-node@v3with:node-version:'18'-name:Restorenode_modulesid:cache-node-modulesuses:actions/cache@v3with:path:node_moduleskey:node-modules-${{hashFiles('yarn.lock')}}-run:|mv.env.test.env-name:Runtestforfilerun:npxhardhattest${{matrix.file}}How Caching Works
First Run (No Cache Available)
Initially, there is no cached data. You can verify this by navigating to GitHub Repository → Actions → Caches.



Subsequent Runs (Using Cache)
When the action runs again, the workflow restores the cached dependencies, reducing installation time significantly.
Cache Invalidation
If new dependencies are installed and the yarn.lock file changes, the hashFiles('yarn.lock') value also changes. This results in a cache miss, forcing the action to install dependencies again and create a new cache entry.
