Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 44 ยท Projects

Project: CI for a Node.js Library

Build a complete CI pipeline for a Node.js library: lint, test matrix, coverage gate, build, publish to npm on a version tag and required status checks.

In this project you will design the complete pipeline for a small open-source Node.js library. It uses almost everything from the earlier chapters: triggers, a matrix, caching, quality gates, a build artifact, a tag-triggered release, least-privilege permissions and branch protection. The goal is a repository where nobody can merge broken code, and where publishing a new version is as simple as pushing a tag.

The library in our story is called tinyslug (a made-up package that turns text into URL slugs). Its repository looks like this:

TEXT
tinyslug/
  src/index.js
  test/index.test.js
  package.json          (scripts: lint, test, build)
  package-lock.json
  .github/
    workflows/
      ci.yml            (pull requests and main)
      release.yml       (version tags)
    dependabot.yml

None of the real workflows can run here because there is no GitHub repository or npm registry on this site, so every YAML file is read-only. The runnable stand-in at the end is a mini pipeline runner that executes the whole plan: it expands the matrix, schedules jobs by their needs, applies the tag condition and shows which events lead to a publish.

The plan

flowchart LR
    PR["Pull request or push to main"] --> L["lint"]
    PR --> T["test<br/>(Node 20, 22, 24)"]
    L --> B["build"]
    T --> B
    B --> OK["ci-ok<br/>(required check)"]
    TAG["Tag v1.2.3"] --> R["release workflow:<br/>verify, then publish"]

CI runs on every change; the release workflow runs only for version tags.

We want these properties:

  1. Every pull request runs lint, tests on three Node versions, a coverage check and a build.
  2. The tests cannot be skipped: one summary job is a required status check.
  3. Releases come from tags such as v1.2.3, never from a laptop.
  4. The npm token (or better, a trusted-publishing identity) is available only to the release job.
  5. Permissions are minimal everywhere.

Step 1: the package scripts

CI should call the same scripts a developer runs. In package.json:

JSON
{
  "name": "tinyslug",
  "version": "1.2.3",
  "type": "module",
  "main": "dist/index.js",
  "files": ["dist"],
  "scripts": {
    "lint": "eslint . --max-warnings 0",
    "test": "node --test --experimental-test-coverage",
    "build": "node scripts/build.mjs",
    "prepublishOnly": "npm run build"
  },
  "engines": { "node": ">=20" }
}

--max-warnings 0 turns lint warnings into failures so they cannot pile up. The engines field documents the supported Node versions that the matrix will verify. The coverage option and its threshold flags depend on your Node version, so check your runtime's documentation when you set a minimum percentage; many projects use a dedicated coverage tool instead.

Step 2: the CI workflow

YAML
name: ci

on:
  pull_request:
  push:
    branches: [main]

concurrency:
  group: ci-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

permissions:
  contents: read

jobs:
  lint:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run lint

  test:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    strategy:
      fail-fast: false
      matrix:
        node: [20, 22, 24]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}
          cache: npm
      - run: npm ci
      - run: npm test
      - uses: actions/upload-artifact@v4
        if: matrix.node == 22
        with:
          name: coverage
          path: coverage/
          if-no-files-found: ignore

  build:
    needs: [lint, test]
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run build
      - run: npm pack --dry-run
      - uses: actions/upload-artifact@v4
        with:
          name: dist
          path: dist/

  ci-ok:
    if: always()
    needs: [lint, test, build]
    runs-on: ubuntu-latest
    steps:
      - name: Fail if anything failed or was cancelled
        run: |
          if [ "${{ contains(needs.*.result, 'failure') }}" = "true" ] || [ "${{ contains(needs.*.result, 'cancelled') }}" = "true" ]; then
            echo "A required job did not succeed."
            exit 1
          fi

Here is why each design choice is there:

  • permissions: contents: read at the top gives every job the least privilege that CI needs (Securing Your Pipeline).
  • concurrency with cancel stops outdated runs when a branch is pushed again. Safe here because this workflow publishes nothing.
  • timeout-minutes on every job protects your minutes from hangs.
  • The matrix (Node 20, 22, 24) proves the library works on each supported runtime. fail-fast: false lets all three finish, so one failure does not hide the results of the others (Matrix Builds).
  • npm ci installs exactly what the lock file says and fails if package.json and the lock file disagree, which is what you want in CI.
  • Caching comes from setup-node with cache: npm, keyed on the lock file.
  • needs: [lint, test] on build means a build never wastes time when checks have failed. npm pack --dry-run lists what would be published, which catches a missing files entry early.
  • ci-ok always runs and is the only job you add as a required check, so renaming matrix entries never breaks branch protection.

Step 3: required checks and protection

In the repository settings, create a branch protection rule (or ruleset) for main:

  • Require a pull request before merging, with at least one approval.
  • Require status checks to pass: select ci-ok only.
  • Require branches to be up to date before merging.
  • Block force pushes and deletions.
  • Optionally restrict who can create v* tags.

Because ci-ok fails when any needed job fails, one required check covers lint, every matrix entry and the build.

Step 4: the release workflow

Publishing happens when someone pushes a tag like v1.2.3 after bumping the version (see Versioning and Automated Releases for ways to automate that part). The workflow re-verifies the code, checks that the tag matches package.json, and publishes.

YAML
name: release

on:
  push:
    tags:
      - "v*.*.*"

permissions:
  contents: read

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm test
      - name: Tag must match package.json
        run: |
          TAG="${GITHUB_REF_NAME#v}"
          VERSION="$(node -p "require('./package.json').version")"
          if [ "$TAG" != "$VERSION" ]; then
            echo "Tag $TAG does not match package.json version $VERSION"
            exit 1
          fi

  publish:
    needs: verify
    runs-on: ubuntu-latest
    environment: npm-release
    permissions:
      contents: write      # create the GitHub release
      id-token: write      # provenance attestation
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
          registry-url: "https://registry.npmjs.org"
      - run: npm ci
      - run: npm run build
      - run: npm publish --provenance --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
      - name: Create a GitHub release
        env:
          GH_TOKEN: ${{ github.token }}
        run: gh release create "$GITHUB_REF_NAME" --generate-notes

Check the security design:

  • Only the publish job has contents: write, id-token: write and the NPM_TOKEN. The verify job, which runs more of your code, does not.
  • The environment: npm-release can require a human reviewer before the job starts, giving you a final "are we sure?" gate (Environments, Approvals and Deployments).
  • Passing the token through env keeps it out of the command line. Some registries also support publishing via short-lived trusted identities instead of long-lived tokens; if yours does, prefer that and delete the stored token.
  • --provenance records where and how the package was built, so consumers can verify it. It requires the id-token permission and a supported registry and environment, so check current npm documentation before relying on it.
  • The tag check blocks the classic mistake of tagging v1.2.4 while package.json still says 1.2.3.

Step 5: keep it fresh

Add .github/dependabot.yml to update both npm packages and the actions in your workflows weekly, as shown in Pipeline Metrics and Maintenance. Because ci-ok gates every pull request, update PRs are tested like any other change.

Stand-in: a mini pipeline runner

The runner below takes the plan as data: the jobs, their needs, the matrix, and an if condition for publishing. It expands the matrix, runs jobs in dependency order, and reports a result for each. A "world" object decides which steps fail, so you can replay scenarios without a real repository. The code mirrors, in simplified form, what GitHub's scheduler does. It does not run shell commands; each job simply consults the scenario.

Node.js Run the whole project plan

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The four runs teach the main rules of the plan. A clean pull request is green but never publishes, because the publish condition requires a version tag. One failing matrix entry makes test fail, skips build, and turns the required check red, so the pull request cannot merge. A tag such as v1.2.3 publishes, and a tag that does not match the version pattern does not.

Extending the project

Try these extensions on your own repository:

  • Add a workflow_dispatch trigger to release.yml with a dry-run input.
  • Generate a changelog from commit messages and attach it to the release.
  • Add a scheduled weekly run of npm audit and a dependency review step on pull requests.
  • Add a Windows entry to the matrix, but only on main, to control cost.
  • Pin every action to a commit SHA and let Dependabot maintain them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is only ci-ok marked as the required status check instead of each job?

    A single always-running summary job gives branch protection one stable name to rely on, and it still covers every job it needs.
  2. 2. Why does the release workflow compare the tag with the version in package.json?

    Tagging one version while the package file says another would publish confusing or wrong metadata. The check fails early.
  3. 3. Which job should have access to the npm token?

    Least privilege: only the job that publishes needs the credential, and an environment can require approval first.
  4. 4. What does fail-fast: false do in the test matrix?

    With fail-fast off, a failure on one Node version does not cancel the others, so you learn exactly which versions are broken.
  5. 5. In the stand-in runner, why does a tag named nightly not publish?

    The onlyIf rule checks the event type and a version pattern such as v1.2.3, so other tag names are ignored.

Summary

  • A good library pipeline has lint, a version matrix, a build and a single required summary check.
  • Use npm ci, dependency caching, timeout-minutes and cancellation of superseded runs.
  • Start from permissions: contents: read and grant extra permissions only to the job that needs them.
  • Release from tags: verify first, check that the tag matches the package version, then publish from a protected environment.
  • Keep the pipeline healthy with Dependabot and a required-check ruleset on main.

Next, you will build and ship a container image with scanning and approvals: Project: Build, Scan and Deploy a Container.