Configure GitHub Actions Matrix CI with npm Caching for Node.js Projects
A practical guide to building a GitHub Actions CI workflow that tests across Node.js 18, 20, and 22 with npm dependency caching, fail-fast behavior, and clear recovery steps for common issues.
16 Sept 2025, 09:36 UTC

Desired Outcome
A reusable GitHub Actions workflow that runs your test suite across Node.js 18, 20, and 22, caches node_modules between runs, and fails fast when any matrix job reports a test failure. The workflow should trigger on every push and pull request, surface per-version status checks on PRs, and reduce total CI time after the first run.
Prerequisites
- A GitHub repository containing a Node.js project managed with npm.
- A
package.jsonwith atestscript (e.g.,"test": "jest"or"test": "vitest run"). - Write access to the repository's Actions settings (Admin or Write role) to create workflow files and manage cache.
- GitHub Actions enabled for the repository (Settings → Actions → General → Allow all actions and reusable workflows).
Procedure
1. Create the workflow file
In your repository root, create .github/workflows/ci.yml with the following content. This file defines a single job test that expands into three matrix legs via strategy.matrix.node-version.
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18, 20, 22]
fail-fast: true
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
Key points:
cache: 'npm'tellssetup-nodeto hashpackage-lock.jsonand restore~/.npm(or the project-local cache) automatically.npm ciperforms a clean, reproducible install using the lockfile; it fails ifpackage-lock.jsonis out of sync.fail-fast: true(the default) cancels remaining matrix jobs as soon as one fails.
2. Commit and push
Run these commands from your local clone (requires git and push permission):
git add .github/workflows/ci.yml
git commit -m "ci: add matrix test workflow with npm caching"
git push origin main
3. Verify the first run
Open the Actions tab in the GitHub UI. You should see a workflow run titled "CI" with three parallel jobs: test (18), test (20), test (22). The first run will show Cache miss for each leg; subsequent runs on the same package-lock.json should show Cache hit.
Expected Checks
- Trigger confirmation: Workflow appears on every push to
mainand on every pull request targetingmain. - Matrix execution: Three distinct jobs run, each reporting the Node version in the setup step log (e.g., "Using node version 20.x.x").
- Cache behavior: First run logs "Cache miss"; later runs with unchanged
package-lock.jsonlog "Cache hit" and skip the bulk ofnpm citime. - Duration reduction: Total workflow wall-clock time should drop noticeably after the first successful run (often 30–60% faster for typical projects).
- PR status checks: Each matrix job appears as a separate required status check on pull requests (e.g., "CI / test (18)").
Recovery Options
Cache corruption or stale artifacts
If npm ci fails with integrity errors or unexpected module versions, the cache may be stale. Two remedies:
- Bump the cache key: Add a suffix to force a new cache entry without deleting the old one. Edit the
setup-nodestep:- name: Set up Node.js ${{ matrix.node-version }} uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} cache: 'npm' cache-dependency-path: package-lock.json # optional: add a manual version bump # cache-key-suffix: v2 - Delete via UI: Go to Settings → Actions → Caches, locate the cache named
npm-, and click the trash icon. Next run will rebuild cleanly.
Flaky tests causing intermittent matrix failures
If a specific test fails sporadically on one Node version, add a retry step for that job only:
steps:
# ... checkout, setup-node, npm ci
- name: Run tests (with retry)
run: npm test
env:
# Example for Jest: retry up to 2 times
JEST_RETRY_TIMES: 2
Alternatively, mark the job as non-blocking for known flaky versions (use sparingly):
strategy:
matrix:
node-version: [18, 20, 22]
include:
- node-version: 18
allow-failure: true
fail-fast: true
Permission errors (GITHUB_TOKEN)
If steps that publish packages or create releases fail with "Resource not accessible by integration", adjust the token permissions at the job or workflow level:
permissions:
contents: read
packages: write # needed for npm publish
id-token: write # needed for OIDC / provenance
Place this at the top of the workflow (applies to all jobs) or inside the test job if you only need elevated scope there.
Limitations & Practical Considerations
- Cache size limit: GitHub Actions caches are capped at 10 GB per repository. Large
node_modules(common with monorepos or heavy native dependencies) can exceed this. If cache saves start failing, consider splitting caches by directory or using a self-hosted runner with local storage. - Cache eviction: Caches not accessed in 7 days are automatically deleted. Infrequent branches may always see a cold cache.
- Minute consumption: Each matrix leg consumes Actions minutes. On private repositories under the free tier, 2,000 minutes/month can be exhausted quickly with a 3× matrix on every push. Consider reducing matrix versions for feature branches or using
if: github.event_name == 'pull_request'to limit full matrix to PRs only. - Node version availability: The
setup-nodeaction may not include the very latest patch or major release immediately. Check the action releases or thenode-versioninput documentation for the current supported list. - Secrets management: Never hardcode npm tokens or other secrets. Store them in Settings → Secrets and variables → Actions (repository or environment scope) and reference as
${{ secrets.NPM_TOKEN }}.
Verification Checklist
- Push a trivial commit (e.g.,
git commit --allow-empty -m "trigger ci") and confirm the workflow runs. - Open a pull request; verify three status checks appear and turn green.
- In a workflow run log, expand the
Set up Node.jsstep and confirm "Cache hit" or "Cache miss" messages. - Visit Settings → Billing & plans → Actions to monitor minute usage after several runs.
- Intentionally break a test (e.g., change an assertion) and push; confirm
fail-fastcancels the other matrix jobs.
Next Steps
Extend this baseline with:
- Code coverage upload via
actions/upload-artifactand a coverage reporter. - Dependency audit step (
npm audit --audit-level=high) as a separate non-blocking job. - Release automation using
semantic-releaseorchangesetson successfulmainbuilds.