Peakiq Blog
How to Publish an NPM Package Automatically with GitHub Actions
Publish NPM packages automatically using GitHub Actions. Learn how to configure tokens, workflows, build steps, and trusted publishing to streamline your NodeJS deployments.
1. Prepare Your Project
Make sure your project has a package.json file with basic information:
{
"name": "your-package-name",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"build": "echo 'Building project...'",
"generate": "echo 'Generating files...'",
"build:all": "npm run build && npm run generate"
},
"repository": {
"type": "git",
"url": "git+https://github.com/your-username/your-repo.git"
},
"author": "Your Name",
"license": "MIT"
}
Here,
build:allwill run bothbuildandgeneratebefore publishing.
2. Push Your Project to GitHub
git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin https://github.com/your-username/your-repo.git
git push -u origin main
3. Create an NPM Token
- Go to NPM Tokens
- Click Create New Token → Classic Token
- Copy the token
Classic tokens work best for CI/CD workflows.
4. Add the Token to GitHub Secrets
- Go to your GitHub repository → Settings → Secrets → Actions → New repository secret
- Name it
NPM_TOKEN - Paste your NPM token and save
5. Add GitHub Actions Workflow
Create a file .github/workflows/publish.yml in your repo:
name: Publish Package
on:
push:
branches:
- main
jobs:
publish-npm:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '20'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: npm install
- name: Build all
run: npm run build:all
- name: Publish to NPM
run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
This workflow runs build:all before publishing to NPM whenever you push to main.
6. Trusted Publisher (Optional but Recommended)
-
Go to your NPM package → Trusted Publisher
-
Select GitHub Actions
-
Fill in:
- Organization/User: your GitHub username
- Repository: your repo name
- Workflow filename:
publish.yml
-
(Optional) Set an Environment for extra security
This allows NPM to verify your GitHub workflow using OpenID Connect (OIDC).
7. Publish Automatically
-
Push any commit to
main -
GitHub Actions will:
- Install dependencies
- Run
npm run build:all - Publish your package to NPM
✅ Conclusion
Now your NPM package is connected with GitHub Actions and publishes automatically. You can focus on development while the workflow handles building and publishing reliably.