Back to Blog

Publishing npm packages with GitHub Actions

Automate your package publishing process using GitHub Actions

Publishing npm packages enables code sharing, collaboration, and seamless integration into projects. Manual publishing is time-consuming and error-prone, but GitHub Actions automate the process.

Publish package on release

We're going to create a GitHub Action that publishes a new version to our private registry every time we create a new GitHub release:

  1. Setup your .npmrc file to publish to your private registry:

    @namespace:registry=https://registry.npm.privatepkgs.com
    //registry.npm.privatepkgs.com/:_authToken=${NODE_AUTH_TOKEN}
    

    Please make sure you replace @namespace with your team's namespace. You can see your namespace by navigating to the package on the Packages tab.

  2. Create the workflow file

    Use the following contents and create a workflow file under .github/workflows/publish.yml:

    name: Publish
    on:
      release:
        types: [published]
    jobs:
      build:
        runs-on: ubuntu-latest
        permissions:
          contents: read
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-node@v3
            with:
              node-version: "20.x"
          - run: npm ci
          - run: npm build
          - run: npm publish
            env:
              NODE_AUTH_TOKEN: ${{ secrets.PRIVATEPKGS_TOKEN }}
    

    We configure the workflow to trigger whenever you create a new release on GitHub. It performs several steps, including checking out the code, setting up Node.js, installing dependencies, building the package, and ultimately publishing the package using the npm publish command.

  3. Add the PRIVATEPKGS_TOKEN secret to your repository

    Note that we provide the environment variable NODE_AUTH_TOKEN for authentication with the registry using the PRIVATEPKGS_TOKEN secret. You should store this token as a secret in your repository settings and refer to it in the workflow file using the secrets context.

    Please ensure that you do not use your personal token. Instead, create and use a team-wide token that you created through the Tokens tab on the dashboard.

  4. Commit and publish a new release

    Commit your changes and create a new release on GitHub. It should trigger a new release of your package. Make sure you have the right version defined in your package.json.

Conclusion

By using GitHub Actions, you can streamline the process of publishing your npm packages. Automating the publishing process not only saves you time but also reduces the chances of human error. With a simple setup, you can ensure that your packages are published automatically whenever you create a new release.