Installing packages from github npm registry - auth error 401

Apparently I'm an idiot who can't read documentation and missed that part:

In the same directory as your package.json file, create or edit an .npmrc file to include a line specifying GitHub Packages URL and the account owner. Replace OWNER with the name of the user or organization account that owns the repository containing your project.

registry=https://npm.pkg.github.com/OWNER


One other thing to check (this took me a while to realize):

I was getting the specified error:

npm ERR! code E401
npm ERR! Unable to authenticate, need: Basic realm="GitHub Package Registry"

Even though I thought I was correctly supplying a GITHUB TOKEN with the needed permissions.

I had set my github action to set the NODE_AUTH_TOKEN from the organization secret named GPR_PRIVATE_READ_TOKEN, which was working in another repo.

Turns out the issue was that the secret was defined to only be available to private repositories and I was trying to use it in a public repository. When I made the secret available to public repositories everything worked.

My workflow job looked like this (I'm showing all steps up to the install step in case it's helpful to someone to see):

jobs:
  ci:
    name: Run Tests
    steps:
      - name: Use Node.js 12.x
        uses: actions/setup-node@v1
        with:
          node-version: 12.x
          registry-url: https://npm.pkg.github.com/

      - uses: actions/checkout@v2

      - name: Install dependencies based on package-lock.json
        run: npm ci
        env:
          NODE_AUTH_TOKEN: ${{ secrets.GPR_PRIVATE_READ_TOKEN }}

You need to generate a personal access token on Github and add it to your npm config in addition to setting the registry in the npm config:

  • In Github navigate to https://github.com/settings/tokens (Settings > Developer settings > Personal access tokens) and you should see something like this:

enter image description here

  • Click Generate new token
  • From the permissions select at least read:packages

enter image description here

  • Click Generate token and copy the token

  • Add the following to your local .npmrc:

    @${OWNER}:registry=https://npm.pkg.github.com
    //npm.pkg.github.com/:_authToken=${TOKEN}
    

See the relevant Github Packages documentation

Related: For Github Actions, be aware of the difference between the GITHUB_TOKEN and a personal access token. The Github Token's permissions are limited to the repository that contains your workflow. For anything else (including granular permissions beyond those allowed for the Github Token) you need a personal access token.