How to Set Up CI for a Next.js App With GitHub Actions
Caching .next/cache alongside npm makes Next.js rebuilds in CI noticeably faster.
Install with npm ci (cached via setup-node), restore the .next/cache directory to speed builds, run next lint, build with next build, then run tests. The build cache is what keeps repeat builds quick.
Steps
- Run
actions/setup-nodewithcache: 'npm'. - Cache
.next/cachekeyed on the lockfile and source files. - Install, then run
npm run lint(next lint). - Build with
npm run buildand runnpm test.
Workflow
.github/workflows/ci.yml
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
build-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- uses: actions/cache@v4
with:
path: ${{ github.workspace }}/.next/cache
key: nextjs-${{ hashFiles('package-lock.json') }}-${{ hashFiles('**/*.ts','**/*.tsx') }}
restore-keys: |
nextjs-${{ hashFiles('package-lock.json') }}-
- run: npm ci
- run: npm run lint
- run: npm run build
- run: npm testGotchas
- Caching
.next/cache(not the whole.next) avoids shipping stale build output between runs. - Set any build-time env vars (such as
NEXT_PUBLIC_*) in the job, or the build can fail.
Related guides
How to Set Up CI for a React App With GitHub ActionsSet up GitHub Actions CI for a Vite React app: setup-node caches npm, npm ci installs, ESLint lints, the app…
How to Set Up CI for Node.js (npm) With GitHub ActionsSet up GitHub Actions CI for a Node.js project that uses npm, with setup-node caching the npm store, npm ci f…