Skip to main content

CI/CD and automation · Intermediate · 18 min

Publish an npm package from GitHub Actions with trusted publishing and provenance

By Padding · Updated 18 Nov 2026
Node.js 26.13.1 · npm 11.20.0 · GitHub Actions

You will have a small npm package that GitHub Actions publishes on each version tag through npm trusted publishing, with no NPM_TOKEN secret and a provenance attestation on every release.

On this page

Publishing an npm package from a laptop works until the laptop is the weak point. A long-lived NPM_TOKEN copied into a CI secret is no better: anyone who gets it can publish any version of your package from anywhere. npm trusted publishing removes the token. npm trusts one workflow file in one GitHub repository, GitHub Actions proves its identity with a short-lived OIDC token at publish time, and npm attaches a provenance attestation that links the release to the commit and the workflow run that built it.

In this tutorial you build tidy-slug, a tiny ES module that turns text into URL slugs, in a throwaway folder, ~/npm-publish-demo. You check exactly which files go into the tarball, try the tarball in a second project, connect the package to a GitHub workflow on npmjs.com, release by pushing a tag, check the provenance, and retire a bad version the way npm intends. The same OIDC idea, a cloud trusting a workflow rather than a stored key, is the subject of /tutorials/deploy-to-aws-from-github-actions-with-oidc.

Step 1 · Create the package

npm package names are global, so publish under your own scope. Set two shell variables first. Replace both values with your own npm username and GitHub user or organisation name, and run every later command in the same terminal so they stay set:

Bash
NPM_SCOPE=your-npm-username   # replace this
GH_OWNER=your-github-name     # replace this
mkdir -p ~/npm-publish-demo/tidy-slug
cd ~/npm-publish-demo/tidy-slug
git init -b main

Write package.json. The heredoc is unquoted so the shell fills in your two names:

Bash
cat > package.json <<JSON
{
  "name": "@${NPM_SCOPE}/tidy-slug",
  "version": "0.1.0",
  "description": "Turn text into URL slugs, dropping accents and tone marks.",
  "type": "module",
  "exports": {
    ".": "./src/index.js",
    "./package.json": "./package.json"
  },
  "files": ["src"],
  "scripts": {
    "test": "node --test"
  },
  "engines": {
    "node": ">=22"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/${GH_OWNER}/tidy-slug.git"
  },
  "license": "MIT",
  "publishConfig": {
    "access": "public"
  }
}
JSON

Four fields do the work in this tutorial:

  • exports is the package's public surface. Code that installs it can import @your-npm-username/tidy-slug and nothing deeper, so you can move files around inside src/ later without breaking anyone.
  • files is an allow-list for the tarball. Only src/ goes in, plus the files npm always adds: package.json, the README and any licence file. Tests, CI config and stray notes stay out.
  • repository.url must match your GitHub repository exactly, or npm rejects the provenance at publish time.
  • publishConfig.access is public because scoped packages are private by default, and private packages need a paid plan.

Now the code. It keeps letters and digits from any script, removes combining marks, so Ẹ kú àárọ̀ becomes e-ku-aaro, and joins everything else with hyphens:

Bash
mkdir -p src test
cat > src/index.js <<'JS'
/**
 * Turn any text into a lower-case, hyphen-separated slug.
 * @param {string} text
 * @returns {string}
 */
export function slugify(text) {
  return String(text)
    .normalize('NFKD')
    .replace(/\p{M}/gu, '')
    .toLowerCase()
    .replace(/[^\p{L}\p{N}]+/gu, '-')
    .replace(/^-+|-+$/g, '')
}
JS
cat > test/index.test.js <<'JS'
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { slugify } from '../src/index.js'

test('lower-cases and joins words with hyphens', () => {
  assert.equal(slugify('Hello, World'), 'hello-world')
})

test('drops accents and tone marks', () => {
  assert.equal(slugify('Ẹ kú àárọ̀'), 'e-ku-aaro')
})

test('keeps letters from non-Latin scripts', () => {
  assert.equal(slugify('ሰላም ዓለም'), 'ሰላም-ዓለም')
})

test('trims separators at both ends', () => {
  assert.equal(slugify('  Lagos 2026  '), 'lagos-2026')
})
JS
cat > README.md <<'MD'
# tidy-slug

`slugify('Ẹ kú àárọ̀')` returns `e-ku-aaro`.
MD
printf 'node_modules\n*.tgz\n' > .gitignore
npm install

The package has no dependencies, so npm install only writes package-lock.json. The workflow later runs npm ci, which needs that file. Removing every combining mark suits Latin, Yorùbá and Ge'ez text, but it would damage scripts such as Devanagari, where vowel signs are marks, so test with the languages your users write before relying on it.

Check it worked

Bash
npm test

The test runner reports tests 4, pass 4 and fail 0.

Step 2 · See exactly what ships

Before anything goes to the registry, ask npm what it would put in the tarball. Add a file that should never ship, then run a dry-run pack:

Bash
printf 'TODO: rename before 1.0\n' > notes.txt
npm pack --dry-run

npm prints a Tarball Contents list with sizes, then Tarball Details with the name, the version, the packed size and the total file count. For scripts, the --json form gives the same list as data:

Bash
npm pack --dry-run --json | node -e '
const [pkg] = JSON.parse(require("fs").readFileSync(0, "utf8"))
console.log(pkg.files.map((f) => f.path).sort().join("\n"))
console.log(`${pkg.size} bytes packed, ${pkg.unpackedSize} bytes unpacked`)
'
rm notes.txt

A package with no dependencies and three small files is a few hundred bytes to download. That matters to the people who install it on prepaid mobile data, and on low-end Android phones running Termux, where every dependency is more to fetch and more to unpack.

Check it worked

The list has exactly three entries: README.md, package.json and src/index.js. notes.txt, test/, .gitignore and package-lock.json are not there, because files allows only src/. If you ever see a .env file or a build cache in this list, fix files before you publish: a version cannot be republished with the same number once it is out.

Step 3 · Install the tarball in a second project

A dry run shows the files, not whether the package works once installed. Build the real tarball one folder up and install it into a separate project, the way a user would get it from the registry:

Bash
npm pack --pack-destination ..
mkdir -p ~/npm-publish-demo/consumer
cd ~/npm-publish-demo/consumer
npm init -y
npm pkg set type=module
npm install ../*-tidy-slug-0.1.0.tgz
cat > check.js <<JS
import { slugify } from '@${NPM_SCOPE}/tidy-slug'
console.log(slugify('Ẹ kú àárọ̀ from Ìbàdàn'))
JS
node check.js

Then try to reach past exports into the package's internals:

Bash
node --input-type=module -e "import('@${NPM_SCOPE}/tidy-slug/src/index.js').catch((e) => console.log(e.code))"
cd ~/npm-publish-demo/tidy-slug

Check it worked

node check.js prints e-ku-aaro-from-ibadan, and the deep import prints ERR_PACKAGE_PATH_NOT_EXPORTED. Your users can only import what exports lists, which is the promise you are making about what counts as a breaking change.

Step 4 · Publish the first version and add a trusted publisher

A trusted publisher is attached to a package that already exists, so the first version goes out from your computer. Create the GitHub repository named tidy-slug under GH_OWNER first (empty, public). Do not tick the options to add a README, .gitignore or licence on GitHub: they create a first commit there, and git push -u origin main is then rejected. Then commit and push:

Bash
git add .
git commit -m "feat: first version of tidy-slug"
git remote add origin "https://github.com/${GH_OWNER}/tidy-slug.git"
git push -u origin main

Log in to npm and publish. npm opens a browser or asks for your two-factor code:

Bash
npm login
npm publish

Version 0.1.0 was published from your laptop, so it has no provenance. Every version after it comes from the workflow.

Now tell npm which workflow may publish. On npmjs.com, open the package, then its Settings tab, and under trusted publishing choose GitHub Actions. Fill in:

  • Organization or user: your GH_OWNER value.
  • Repository: tidy-slug.
  • Workflow filename: publish.yml, the file name only, without .github/workflows/.
  • Environment name: npm. The workflow's publish job runs in a GitHub environment of that name, so you can add required reviewers later, as in /tutorials/require-approval-before-production-deploys-with-github-environments.
  • Allowed actions: allow direct npm publish. Configurations made since September 2026 allow only staged publishing unless you tick it.

npm does not check these values when you save. A typo shows up as a failed publish, and the connection cannot be edited, only deleted and created again. A new connection must complete a successful publish within two days, so do the next two steps the same day. With npm 11.15 or later you can also manage the connection from the terminal with npm trust github, and list it with:

Bash
npm trust list "@${NPM_SCOPE}/tidy-slug"

Finally, close the old door. In the package's Settings, under publishing access, choose Require two-factor authentication and disallow tokens. The trusted publisher keeps working, because it never used a token, and a leaked token from anywhere else can no longer publish.

Check it worked

The package page on npmjs.com shows version 0.1.0, npm trust list shows one GitHub Actions entry for your repository and publish.yml, and the publishing access setting says tokens are disallowed. If you are on a team, there are now no npm tokens for this package to rotate when someone leaves.

Step 5 · Write the publish workflow

The workflow runs when a tag starting with v is pushed. The tests run first in a job with no special rights. Only the publish job can ask GitHub for an OIDC token:

Bash
mkdir -p .github/workflows scripts
cat > .github/workflows/publish.yml <<'YAML'
name: Publish to npm

on:
  push:
    tags: ['v*']

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          package-manager-cache: false
      - run: npm ci
      - run: npm test

  publish:
    needs: test
    runs-on: ubuntu-latest
    environment: npm
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          registry-url: https://registry.npmjs.org
          package-manager-cache: false
      - run: npm ci
      - run: node scripts/check-tag.mjs
      - run: npm publish
YAML

The tag check stops a release when someone tags v0.2.0 but forgot to change package.json, or the other way round:

Bash
cat > scripts/check-tag.mjs <<'JS'
import { readFileSync } from 'node:fs'

const { version } = JSON.parse(readFileSync('package.json', 'utf8'))
const tag = process.env.GITHUB_REF_NAME

if (tag !== `v${version}`) {
  console.error(`Tag ${tag} does not match package.json version ${version}`)
  process.exit(1)
}
console.log(`Tag ${tag} matches package.json version ${version}`)
JS

What each part does:

  • id-token: write lets the publish job request an OIDC token from GitHub. npm 11.20, bundled with Node.js 26, sees it, exchanges it for a one-off publish credential and generates the provenance attestation. There is no --provenance flag and no NODE_AUTH_TOKEN because neither is needed.
  • registry-url writes an .npmrc that points at the public registry.
  • package-manager-cache: false turns off setup-node's automatic npm cache. A cache restored into a job that can publish is one more thing an attacker could try to poison, and this package has nothing to cache.
  • persist-credentials: false stops checkout leaving a GitHub token in .git/config for later steps to read.
  • environment: npm must match the environment name you typed on npmjs.com. If you left that field empty, remove this line.
  • The action tags (@v7) are fine to start with. /tutorials/harden-github-actions-workflows shows how to pin them to commit SHAs, which matters most in a job like this one.

Trusted publishing works on GitHub-hosted runners. Self-hosted runners are not supported yet, so keep runs-on: ubuntu-latest.

Check it worked

Lint the workflow, then run the commands the jobs run, including the tag check with a matching and a wrong tag:

Bash
actionlint
echo "actionlint exit code: $?"
npm ci
npm test
GITHUB_REF_NAME=v0.1.0 node scripts/check-tag.mjs
GITHUB_REF_NAME=v9.9.9 node scripts/check-tag.mjs || echo "wrong tag refused"

actionlint prints nothing and the exit code is 0. The tests pass, the first check prints Tag v0.1.0 matches package.json version 0.1.0, and the second prints Tag v9.9.9 does not match package.json version 0.1.0 followed by wrong tag refused. scripts/ is not in files, so the check never ships to users; run npm pack --dry-run again if you want to see that.

Step 6 · Release a version by pushing a tag

Commit the workflow, then let npm bump the version. npm version patch changes package.json and package-lock.json, commits them and creates a matching v tag in one go:

Bash
git add .
git commit -m "ci: publish to npm with trusted publishing"
npm version patch -m "chore: release %s"

Push the commit and the tag together:

Bash
git push origin main --follow-tags

Open the Actions tab in your repository. The Publish to npm run starts from the tag push, the test job goes green, then publish runs and its last log lines show + @your-npm-username/tidy-slug@0.1.1 along with a line saying a provenance statement was signed and published to the transparency log.

If the publish job fails with an authentication or 404 error, the trusted publisher values do not match the run: compare the owner, repository, workflow file name and environment on npmjs.com with the run, check repository.url in package.json, and confirm direct publishing is allowed.

Check it worked

Bash
git log --oneline -1
git tag
node -p "require('./package.json').version"

The newest commit is chore: release 0.1.1, git tag lists v0.1.1, and package.json says 0.1.1. On GitHub, the run for v0.1.1 is green.

Step 7 · Check provenance and registry signatures

On the package page on npmjs.com, version 0.1.1 now has a green check mark in the Version field. Click it, then View more details: the provenance section links to the workflow run, the source commit, the workflow file that built it and the public transparency-log entry. Version 0.1.0, published from your laptop, has none. From the terminal:

Bash
npm view "@${NPM_SCOPE}/tidy-slug@0.1.1" dist.attestations.provenance.predicateType

It prints https://slsa.dev/provenance/v1. For 0.1.0 it prints nothing.

Your users check signatures from their side with npm audit signatures, which verifies the registry signature of every installed package and the attestations of those that have them. Try it in a fresh folder with a package that already ships provenance, semver 7.8.6:

Bash
mkdir -p ~/npm-publish-demo/audit-check
cd ~/npm-publish-demo/audit-check
npm init -y
npm install --save-exact semver@7.8.6
npm audit signatures
npm view semver@7.8.6 dist.attestations.provenance.predicateType
cd ~/npm-publish-demo/tidy-slug

Check it worked

npm audit signatures reports something like 1 package has a verified registry signature and 1 package has a verified attestation, and exits with 0. npm view prints https://slsa.dev/provenance/v1. Add npm audit signatures after npm ci in your other projects' workflows, as /tutorials/automate-releases-with-semantic-release does, so a tampered dependency fails the build.

Step 8 · Deprecate a bad version instead of unpublishing

Suppose 0.1.1 turns out to break on some input. Unpublishing looks tempting, but npm only allows it within 72 hours of publishing, or later for packages with fewer than 300 downloads a week, no dependents and a single owner. Even then the version number can never be used again, and anyone whose lock file names it gets an install failure. Deprecating keeps the version installable and prints your message to everyone who installs it.

Run this from your computer, logged in to npm. Trusted publishing covers publishing, not deprecation:

Bash
npm deprecate "@${NPM_SCOPE}/tidy-slug@0.1.1" "Breaks on empty input. Upgrade to 0.1.2 or later."

Then fix the bug, release 0.1.2 the same way as before (npm version patch, then git push origin main --follow-tags), and let the workflow publish it. If you deprecated the wrong version, an empty message removes the deprecation:

Bash
npm deprecate "@${NPM_SCOPE}/tidy-slug@0.1.1" ""

You can deprecate a whole range, such as "@${NPM_SCOPE}/tidy-slug@<0.1.2", when several versions share the same bug.

Check it worked

Bash
npm view "@${NPM_SCOPE}/tidy-slug@0.1.1" deprecated

It prints your message, and the npm package page marks 0.1.1 as deprecated. Installing @your-npm-username/tidy-slug@0.1.1 in a fresh folder shows an npm warn deprecated line with the same text.

When you are finished, delete the local demo. This removes the demo folders only; the package stays on npm and the repository stays on GitHub until you remove them there:

Bash
rm -rf ~/npm-publish-demo

Next steps

  • Let commit messages pick the version and run npm publish for you: /tutorials/automate-releases-with-semantic-release.
  • Pin actions to commit SHAs and audit the workflow with zizmor: /tutorials/harden-github-actions-workflows.
  • Use the same OIDC trust to deploy to a cloud without stored keys: /tutorials/deploy-to-aws-from-github-actions-with-oidc.
  • Run the test job across Node.js versions before you publish: /tutorials/run-node-tests-in-github-actions.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.