Automating npm Package Publication with GitHub Actions
Introduction
Recently, I’ve been developing several npm packages for personal projects. It was becoming a hassle to build and run npm publish
locally every time I needed to release a new version.
So, I automated the publication process using GitHub Actions and I’m summarizing the steps here.
Procedure
Creating an npm Access Token
First, click on your npm account icon and navigate through the menu: Access Tokens > Generate New Token > Granular Access Token
to reach the token creation page.
Set the permissions in Packages and scopes
to Read and Write
, fill in the remaining fields, and create the token.
Setting up GitHub Actions
Next, go to your GitHub repository’s settings, navigate through Secrets and variables > Actions > Repository secrets
, and set up a secret using the npm access token you just created. Let’s name the secret NPM_ACCESS_TOKEN
. This makes the access token available in the workflow as ${{ secrets.NPM_ACCESS_TOKEN }}
.
Then, create a workflow file. In the example below, the trigger is set for tag pushes, but feel free to modify it as you like.
name: Release
on:
push:
tags:
- '*'
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v4
- name: Setup node
uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Install npm packages
run: npm ci
- name: build
run: npm run build
- name: Publish to npm
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_ACCESS_TOKEN }}
Points to note:
- The environment variable name to pass during
npm publish
isNODE_AUTH_TOKEN
- If you’re publishing a public package, use
npm publish --access public
- In the
setup-node
step, it’s necessary to set theregistry-url
tohttps://registry.npmjs.org/
The complete workflow is available in the following repository, feel free to use it as a reference. It also includes the process for creating release notes.
Conclusion
It’s truly convenient how easy it is to set up GitHub Actions, thanks to the well-organized documentation.
Glad to eliminate one more redundant task from the world.