Unable to authenticate, need: Basic realm="GitHub Package Registry" when trying to publish npm package to github

I am currently trying to publish a package to the Github registry.

The package is generated code, although this should not really matter here. The important thing is that I have the following:

The package.json file contains:

{
    "name": "@company-name/repository-name",
    "version": "v1.7.0",
    "repository": "git://github.com/@company-name/repository-name.git"
}

The .npmrc file reads:

@company-name:registry=https://npm.pkg.github.com

Whereas this is what I am running in my Github Action:

      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: '12.x'
          registry-url: 'https://npm.pkg.github.com'
          # Defaults to the user or organization that owns the workflow file
          scope: '@company-name'

      # ...

      - name: Install and publish
        working-directory: .generated/
        run: |
          sudo npm install
          sudo npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

I am following the docs but it seems I am missing something.

Log output

npm notice === Tarball Details === 
npm notice name:          @company-name/repository-name
npm notice version:       1.7.0                                      
npm notice package size:  11.6 kB                                    
npm notice unpacked size: 104.6 kB                                   
npm notice shasum:        2262a7f9ef1bb95b1d6ae2dc92095d04eb2a22b6   
npm notice integrity:     sha512-WaJvaoZV8uo2Y[...]Re2hW2A/BIO5Q==   
npm notice total files:   24                                         
npm notice 
npm ERR! code E401
npm ERR! Unable to authenticate, need: Basic realm="GitHub Package Registry"

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-09-03T19_27_04_437Z-debug.log
Error: Process completed with exit code 1.

Solution 1:

The way we were able to get around this issue was by adding a simple script to the action:

    - name: Install Dependencies
      run: |
        echo "@INSERT_ORG_NAME:registry=https://npm.pkg.github.com" > .npmrc
        echo "//npm.pkg.github.com/:_authToken=$GITHUB_PAT" >> .npmrc
        npm install
      env:
        GITHUB_PAT: ${{ secrets.REPO_READ_PAT }}

Second line is because we're dealing with a private repo.