GitHub Actions Caching & Artifacts
Accelerate pipeline speeds with dependency and build caching, and pass compiled binaries and test reports between jobs with artifacts.
GitHub Actions Caching & Artifacts
Optimizing CI/CD execution speed and retaining build outputs requires understanding the difference between Caching and Artifacts.
1. Caching vs Artifacts
| Feature | Caching (actions/cache) | Artifacts (actions/upload-artifact) |
|---|---|---|
| Purpose | Reusing dependencies and build caches to speed up runs | Saving test reports, coverage, and compiled binary releases |
| Lifecycle | Persisted across different workflow runs for up to 7 days | Stored for 90 days (configurable) for download in GitHub UI |
| Job Sharing | Used across different workflow runs on same branch/default branch | Passed between different jobs within the same workflow run |
| Storage Limit | 10 GB per repository | Consumes GitHub Actions storage quota |
2. Dependency Caching
2.1 Native Setup Actions (Recommended)
Official setup actions provide built-in package manager caching:
- name: Setup Node.js with PNPM cache
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'pnpm'2.2 Explicit Caching with actions/cache@v4
For custom directories like Next.js build cache:
- name: Cache Next.js build cache
uses: actions/cache@v4
with:
path: |
~/.npm
${{ github.workspace }}/.next/cache
# Generate a unique key based on lockfiles and source files
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/pnpm-lock.yaml') }}-${{ hashFiles('**.[jt]s', '**.[jt]sx') }}
# Fallback to restore cache from previous commit if exact key misses
restore-keys: |
${{ runner.os }}-nextjs-${{ hashFiles('**/pnpm-lock.yaml') }}-3. Passing Artifacts Between Jobs
Use upload-artifact and download-artifact to compile once and reuse across testing or deployment jobs:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
- run: pnpm build
# Upload the production build output
- name: Upload production artifact
uses: actions/upload-artifact@v4
with:
name: web-dist
path: .next/standalone
retention-days: 7
deploy:
needs: build
runs-on: ubuntu-latest
steps:
# Download artifact generated by build job
- name: Download web build
uses: actions/download-artifact@v4
with:
name: web-dist
path: ./dist
- name: Verify build files
run: ls -la ./distGitHub Actions Secrets & Environment Variables
Securely manage credentials, repository secrets, environment variables, automatic GITHUB_TOKEN, and prevent credential exposure in CI/CD.
GitHub Actions Matrix Builds
Test across multiple operating systems, Node.js runtimes, and databases simultaneously using GitHub Actions matrix strategies.