CI/CD and automation · Intermediate · 16 min
Cache dependencies and build outputs in GitHub Actions
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · GitHub Actions (actions/cache v6, setup-node v7, setup-python v7) · actionlint 1.7.12
You will have a GitHub Actions workflow that restores npm packages and a Next.js build cache under keys you designed, skips the install on an exact hit, and passes actionlint, plus a script that shows the keys on your own machine.
On this page
A cold CI run downloads every package it needs, then rebuilds every page from nothing. Most of that work is the same as last time. A cache stores a folder at the end of one run and puts it back at the start of the next, so the job only fetches and builds what changed.
The difficult part is not the YAML. It is choosing what to cache and under which key, so that the cache helps when nothing changed and gets out of the way when something did. In this tutorial you will take a small repository with a Next.js front end and a Python helper script, try the caching built into setup-node and setup-python, then write your own keys with actions/cache for node_modules and for the Next.js build cache. A short script reproduces GitHub's hashFiles() on your machine so you can see each key before you push.
Everything happens in a throwaway folder, ~/cache-demo. In your own project the lock files and source folders already exist; the ones here are small stand-ins with the same names. The demo folder is not a git repository and has no real Next.js install, so it is for checking files and keys locally, not for pushing. To see the caches work on GitHub, copy ci.yml (and builtin.yml only if your project has scripts/requirements.txt) into your own Next.js repository, adjust the paths, push, and run the workflow twice.
Step 1 · Set up the demo repository and actionlint
Create the folder and the files a Next.js project with a Python script folder would have. The lock file here lists no packages, which is enough for hashing:
mkdir -p ~/cache-demo/src/app ~/cache-demo/scripts ~/cache-demo/.github/workflows
cd ~/cache-demo
cat > package.json <<'JSON'
{
"name": "cache-demo",
"version": "1.0.0",
"private": true,
"scripts": {
"build": "next build"
}
}
JSON
cat > package-lock.json <<'JSON'
{
"name": "cache-demo",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cache-demo",
"version": "1.0.0"
}
}
}
JSON
cat > next.config.mjs <<'JS'
const nextConfig = {}
export default nextConfig
JS
cat > src/app/page.js <<'JS'
export default function Home() {
return <h1>Cache demo</h1>
}
JS
cat > scripts/requirements.txt <<'TXT'
httpx==0.28.1
TXTInstall actionlint, a checker for workflow files, from its GitHub releases (version 1.7.12 here). On macOS, brew install actionlint does the same. On Linux:
sudo apt update
sudo apt install -y curl ca-certificates
ARCH="$(uname -m)"
case "$ARCH" in
x86_64) ARCH=amd64 ;;
aarch64) ARCH=arm64 ;;
esac
mkdir -p ~/.local/bin
curl -fsSL "https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_${ARCH}.tar.gz" | tar -xz -C ~/.local/bin actionlint
export PATH="$HOME/.local/bin:$PATH"A binary downloaded this way gets no updates from apt. To upgrade, run the same curl line with the newer version number from github.com/rhysd/actionlint/releases.
Check it worked
actionlint -version | head -n 1
ls -A ~/cache-demoThe first line prints 1.7.12. The listing shows .github, next.config.mjs, package-lock.json, package.json, scripts and src.
Step 2 · Start with the cache built into the setup actions
The setup actions for each language can cache the package manager's download folder for you. You name the package manager; the action finds the lock file, builds a key from it and the runner's operating system, restores on the way in and saves at the end of the job. Write a workflow that uses both:
cat > .github/workflows/builtin.yml <<'YAML'
name: Built-in caching
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
web:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
id: node
with:
node-version: 26
cache: npm
- run: |
echo "npm cache restored exactly: ${{ steps.node.outputs.cache-hit }}"
- run: npm ci
- run: npm run build
scripts:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: '3.15'
cache: pip
cache-dependency-path: scripts/requirements.txt
- run: pip install -r scripts/requirements.txt
YAMLWhat each part caches:
cache: npmsaves npm's own download store (~/.npmon Linux), notnode_modules.npm cistill deletes and rebuildsnode_moduleson every run; it reads the tarballs from the store instead of the network.cache: pipsaves pip's download and wheel folder.cache-dependency-pathtells it which file to hash, because the requirements file is not at the root.- Neither covers build output. The
.next/cachefolder that makes a Next.js rebuild fast is not touched.
For many projects this is all you need. Reach for actions/cache when you want to cache something the setup action does not know about, control the key yourself, or skip a step when the cache is exact.
Check it worked
actionlint .github/workflows/builtin.yml
echo "actionlint exit code: $?"The run: | form keeps the colon inside the message from being read as YAML. No messages and exit code 0 mean the file is valid, including the step id node that steps.node.outputs.cache-hit refers to.
Step 3 · See the keys GitHub will compute
A key is a plain string. Build it from things that, when they change, should make the old cache wrong. For installed packages that is the lock file and the operating system, because a package built on Linux may not work on Windows:
key: ${{ runner.os }}-modules-${{ hashFiles('package-lock.json') }}On ubuntu-latest, runner.os is Linux. hashFiles() takes a SHA-256 of each matching file, feeds those hashes into one more SHA-256, and returns that as hex. It returns an empty string when nothing matches, which gives you a key like Linux-modules-, so check the file name. Save this script to print the same value locally:
cat > ~/cache-demo/cache-key.sh <<'SH'
#!/usr/bin/env bash
# Print the value hashFiles() gives for the files named, in the order given.
set -euo pipefail
sha() {
if command -v sha256sum >/dev/null 2>&1; then sha256sum; else shasum -a 256; fi
}
joined=""
for f in "$@"; do
inner="$(sha < "$f" | cut -d' ' -f1)"
joined+="$(printf '%s' "$inner" | sed 's/../\\x&/g')"
done
printf "$joined" | sha | cut -d' ' -f1
SH
chmod +x ~/cache-demo/cache-key.shFor one file the result matches GitHub exactly. With a pattern that matches several files, GitHub hashes them in the order its file search finds them, so the value for a glob can differ from yours. The behaviour you care about is the same: change any file and the key changes.
Check it worked
Print the key, change the lock file the way an upgrade would, and print it again:
KEY_BEFORE="Linux-modules-$(./cache-key.sh package-lock.json)"
echo "$KEY_BEFORE"
cat > package-lock.json <<'JSON'
{
"name": "cache-demo",
"version": "1.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cache-demo",
"version": "1.1.0"
}
}
}
JSON
KEY_AFTER="Linux-modules-$(./cache-key.sh package-lock.json)"
echo "$KEY_AFTER"
for KEY in "$KEY_BEFORE" "$KEY_AFTER"; do
if [[ "$KEY" =~ ^Linux-modules-[0-9a-f]{64}$ ]]; then
echo "key has the expected form"
else
echo "unexpected key: $KEY"; false
fi
done
if [ "$KEY_BEFORE" != "$KEY_AFTER" ]; then
echo "lock file changed, so the key changed"
else
echo "key did not change"; false
fiYou see two keys, both starting Linux-modules- and followed by 64 hex characters, two key has the expected form lines, then lock file changed, so the key changed. The second run of a workflow after this change misses the old cache and saves a new one.
Step 4 · Cache installed packages and skip the install on an exact hit
Now write the main workflow. The first cache holds node_modules itself. Restoring it on an exact key match means the install step has nothing to do, so the workflow skips it:
cat > .github/workflows/ci.yml <<'YAML'
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 26
- name: Restore node_modules
id: deps
uses: actions/cache@v6
with:
path: node_modules
key: ${{ runner.os }}-node26-modules-${{ hashFiles('package-lock.json') }}
- name: Install dependencies
if: steps.deps.outputs.cache-hit != 'true'
run: npm ci
- run: npm run build
YAMLPoints to notice:
setup-nodehas nocache:line here. Caching the same packages twice wastes the repository's cache space. If your ownpackage.jsonhas apackageManager(ordevEngines.packageManager) field naming npm,setup-nodeturns npm caching on by itself; addpackage-manager-cache: falseunder itswith:to stop that.- The key includes
node26. Packages with native parts are compiled for one Node.js version, so a change of version needs a freshnode_modules. - There is no
restore-keyson this cache, on purpose. A partial match would restore anode_modulesbuilt from an older lock file, and with the install skipped nothing would correct it. cache-hitis'true'only for an exact key match. It is'false'when a restore key matched, and empty when nothing was restored. Compare it with!= 'true'so both of the other cases run the install.
actions/cache saves at the end of the job, and only when the job succeeds and the key did not already exist. Caches cannot be changed once saved; new content needs a new key.
Check it worked
actionlint .github/workflows/ci.yml
echo "actionlint exit code: $?"Exit code 0. Then see what happens when a condition points at a step id that does not exist, a mistake that otherwise makes the install run every time without any error:
sed 's/steps\.deps\./steps.dep./' .github/workflows/ci.yml > /tmp/ci-typo.yml
if actionlint /tmp/ci-typo.yml; then
echo "expected actionlint to report the typo"; false
else
echo "actionlint caught the wrong step id"
fi
rm /tmp/ci-typo.ymlactionlint prints a message naming dep as a property that is not defined, with the line and column, and the last line reads actionlint caught the wrong step id.
Step 5 · Cache the Next.js build output separately
next build keeps compiled modules and optimised images in .next/cache, and reuses them on the next build. That folder changes with your source code, while node_modules changes with the lock file. Give it its own cache and its own key, so editing a page does not throw away your packages, and upgrading a package does not leave stale build output behind.
Add this step to ci.yml between the install and the build. Rewrite the whole file so the order is exact:
cat > .github/workflows/ci.yml <<'YAML'
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 26
- name: Restore node_modules
id: deps
uses: actions/cache@v6
with:
path: node_modules
key: ${{ runner.os }}-node26-modules-${{ hashFiles('package-lock.json') }}
- name: Install dependencies
if: steps.deps.outputs.cache-hit != 'true'
run: npm ci
- name: Restore Next.js build cache
uses: actions/cache@v6
with:
path: .next/cache
key: ${{ runner.os }}-nextjs-${{ hashFiles('package-lock.json') }}-${{ hashFiles('src/**', 'next.config.mjs') }}
restore-keys: |
${{ runner.os }}-nextjs-${{ hashFiles('package-lock.json') }}-
- run: npm run build
YAMLHere restore-keys is safe and useful. When you change one page, the full key misses, but the prefix Linux-nextjs-<lock hash>- matches the most recent cache saved for the same packages. Next.js then rebuilds only what changed, and the job saves a new cache under the full key. If the lock file changed too, the prefix misses and the build starts clean, which is what you want after an upgrade.
Restore keys are tried in order, and each one matches the newest cache whose key starts with it. Keep them from most specific to least.
Check it worked
Compute both keys locally, then edit a page and compute them again:
actionlint .github/workflows/ci.yml
LOCK="$(./cache-key.sh package-lock.json)"
SRC_BEFORE="$(./cache-key.sh $(find src -type f | sort) next.config.mjs)"
PREFIX="Linux-nextjs-${LOCK}-"
echo "full key: ${PREFIX}${SRC_BEFORE}"
echo "restore key: ${PREFIX}"
cat > src/app/page.js <<'JS'
export default function Home() {
return <h1>Cache demo, second version</h1>
}
JS
SRC_AFTER="$(./cache-key.sh $(find src -type f | sort) next.config.mjs)"
NEW_KEY="${PREFIX}${SRC_AFTER}"
echo "new key: ${NEW_KEY}"
if [ "$SRC_BEFORE" != "$SRC_AFTER" ]; then
echo "page edit changed the full key"
else
echo "full key did not change"; false
fi
case "$NEW_KEY" in
"$PREFIX"*) echo "restore key still matches, so the last build cache is reused" ;;
*) echo "restore key no longer matches"; false ;;
esacactionlint prints nothing. The full key changes after the edit, the restore key stays the same, and the last line confirms the prefix still matches.
Step 6 · Know who can read a cache and how long it lasts
A cache is saved for the branch or tag the run was on, and its reach is narrower than many people expect:
- A run can restore caches saved on its own branch and on the default branch (usually
main). A pull request run can also restore caches from its base branch. - A branch cannot read caches from a sibling branch, or from a branch created from it. Two feature branches never share a cache, so warm
mainfirst: a run onmainafter each merge saves the caches every new branch starts from. - A run on a tag cannot restore caches saved for a different tag.
- A pull request run saves its caches for the pull request's merge ref, so only later runs of that same pull request can use them.
Space is shared across the whole repository. By default the limit is 10 GB per repository. GitHub removes entries that nobody has restored for 7 days, and when the repository goes over its limit it deletes the caches that were used least recently first. A large build cache saved on every branch can push out the dependency caches main relies on, so keep build caches to the folders that pay for themselves.
If you run a self-hosted runner on a metered or prepaid connection, as many teams in Nigeria and across Africa do, a cache restore is still a download from GitHub's storage. Restoring a 2 GB .next/cache can use more data than the build saves time. Watch the size the cache step prints in its log, and drop a cache that is mostly bytes moved.
Check it worked
This check needs a real repository, not ~/cache-demo: copy ci.yml (and builtin.yml only if you have scripts/requirements.txt) into your own Next.js repository, adjust the paths, push it and let CI run twice. actions/cache only saves when the job succeeds, so the build has to pass. Then list the repository's caches with the GitHub CLI, run in your repository folder:
gh cache listEach row shows a key such as Linux-node26-modules-… and Linux-nextjs-…, its size, the ref it belongs to (refs/heads/main or a refs/pull/<number>/merge ref) and when it was last used. The same list is under Caches in the repository's Actions tab. On the second run of CI on the same commit, the Restore node_modules step logs an exact hit and Install dependencies shows as skipped.
To clear a cache you no longer want, for example after renaming its key, replace <key> with the key from the list:
gh cache delete <key>When you have finished with the demo, remove it and the actionlint binary if you installed it only for this:
rm -rf ~/cache-demo
rm -f ~/.local/bin/actionlintNext steps
- Run tests on every push with the setup-node cache in place: /tutorials/run-node-tests-in-github-actions
- Add
matrixvalues to your keys when one workflow builds on several systems and versions: /tutorials/run-a-build-matrix-across-operating-systems-and-versions - Move these cache steps into one shared composite action instead of copying them between repositories: /tutorials/write-reusable-workflows-and-composite-actions
- Read GitHub's reference on cache scope and limits, which changes over time: docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching
Related tutorials
- How to Run Node.js Tests Automatically with GitHub ActionsYou will write tests with Node.js's built-in test runner, run them on every push and pull request with a GitHub Actions workflow that caches npm downloads and tries two Node.js versions, and check the workflow file locally before you push it.
- Run a GitHub Actions build matrix across operating systems and versionsYou will have a GitHub Actions workflow that tests one Node.js project on Linux, macOS and Windows across three Node.js versions, with trimmed and added legs, an experimental nightly leg that cannot fail the run, and a matrix generated by a script that keeps pull request runs small.
- How to Create Your First GitHub Actions WorkflowYou will write a workflow file that runs on every push and every pull request, check its syntax on your own computer with actionlint, push it, and read the run on GitHub.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials