32

This question is related to these. But none of the solutions worked for me.

I can install a package without issues with npm install @scope/package however I cannot do the same with yarn: yarn add @scope/package

yarn throws the following error: An unexpected error occurred: "https://npm.pkg.github.com/download/@scope/package/1.2.8/089b08cffb16074c210ec3a59b04de268ae1c7b3a0492dce110adee3ada05bdd: Request failed \"401 Unauthorized\"".

my .npmrc file looks like this: (tried with and without below .yarnrc)

registry=https://registry.npmjs.org/
//npm.pkg.github.com/:_authToken=MY_AUTHTOKEN
@scope:registry=https://npm.pkg.github.com/

I have tried adding this .yarnrc file:

registry "https://registry.npmjs.org"
"@scope:registry" "https://npm.pkg.github.com"

(without .yarnrc) I've tried this .npmrc file

registry=https://registry.yarnpkg.com/

@scope:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=MY_AUTHTOKEN
always-auth=true

Where MY_AUTHTOKEN is my Personal Access Token I've generated from Github. (it has access to everything in packages)

I have tried to:

  • remove yarn.lock
  • remove .yarnrc
  • login with npm login using my PAT as the password
  • logout of npm and removing global .npmrc and .yarnrc
  • logging in with yarn login

In case of any confusion I'm not actually trying @scope and /package but my actual scope and package name.

I do have access to the scope and package on Github.

and again my first setup works just fine with npm. But I cannot get this working with yarn, and cannot find any valid existing solution on SO.

1
  • You say you solved this with Yarn 2. Could you explain how? It's not clear. Commented Jul 26, 2022 at 16:25

7 Answers 7

50
+50

The following worked for me in .npmrc

@mvce-superstars:registry=https://npm.pkg.github.com

Using yarn v2, the following worked for me in .yarnrc.yml:

npmScopes:
  "mvce-superstars":
    npmAlwaysAuth: true
    npmAuthToken: xxx-xxx # optional
    npmRegistryServer: "https://npm.pkg.github.com"

Note

The scope name is lowercase. This is supposed to be the name of the owner of the repository (ex. MVCE-Superstars) where the package was published, but the name has to be all lower-cased.


The setup

Publishing

  • I created a private copy of this hello-world repository.
  • I copied over the above .npmrc OR .yarnrc.yml file into the repoository.
  • Next I logged in using the npm login --registry=https://npm.pkg.github.com/ OR yarn npm login --scope=mvce-superstars command (skip if npmAuthToken is specified above)
  • I entered my github user name, and my token (with scopes read:package, write:package, and repo) (skip if npmAuthToken is specified above)
  • Finally, I pushed the package to my private repo using npm publish OR yarn npm publish

Output

npm notice 
npm notice 📦  @mvce-superstars/[email protected]
npm notice === Tarball Contents === 
npm notice 16.3kB example.gif   
npm notice 89B    bin.js        
npm notice 175B   lib/index.js  
npm notice 734B   package.json  
npm notice 2.0kB  yarn-error.log
npm notice 570B   Readme.md     
npm notice 167B   init.sh       
npm notice === Tarball Details === 
npm notice name:          @mvce-superstars/hello-world-npm        
npm notice version:       1.1.1                                   
npm notice package size:  14.3 kB                                 
npm notice unpacked size: 20.0 kB                                 
npm notice shasum:        5379c8030fa9c5f57e5baef67f2a8a784ce93361
npm notice integrity:     sha512-FAI/Wuy4gHW8C[...]FINQeIlZ+HDdg==
npm notice total files:   7                                       
npm notice 
+ @mvce-superstars/[email protected]

Downloading

  • I create a new npm project using npm init (use-hello-world-npm)
  • I copy the above .npmrc to the root of the folder
  • Next I logout of npm (npm logout --registry=https://npm.pkg.github.com/) and log back in (npm login --registry=https://npm.pkg.github.com/), just to be sure
  • Finally, I run yarn and like it was supposed to, it worked!

Output

yarn install v1.22.4
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
Done in 0.55s.

yarn v2

➤ YN0000: ┌ Resolution step
➤ YN0014: │ @mvce-superstars/hello-world-npm@npm:^1.1.1: Only some patterns can be imported from legacy lockfiles (not "https://npm.pkg.github.com/download/@mvce-superstars/hello-world-npm/1.1.1/426126f89734c2c76bfac0342c1de9c95ad003b6e905a7b9f9f745892c86da7a#5379c8030fa9c5f57e5baef67f2a8a784ce93361")
➤ YN0000: └ Completed in 0.55s
➤ YN0000: ┌ Fetch step
➤ YN0013: │ @mvce-superstars/hello-world-npm@npm:1.1.1::__archiveUrl=https%3A%2F%2Fnpm.pkg.github.com%2Fdownload%2F%40mvce-superstars%2Fhello-world-npm%2F1.1.1%2F426126f89734c2c76bfac0342c1de9c95ad003b6e905a7b9f9f745892c86da7a can't be found in the cache and will be fetched from the remote server
➤ YN0000: └ Completed in 1.3s
➤ YN0000: ┌ Link step
➤ YN0031: │ One or more node_modules have been detected and will be removed. This operation may take some time.
➤ YN0000: └ Completed
➤ YN0000: Done with warnings in 1.87s

Contents of folder after yarn

.
├── node_modules
│   └── @mvce-superstars
├── package.json
└── yarn.lock

And for good measure, I remove it (yarn remove @mvce-superstars/hello-world-npm):

yarn remove v1.22.4
[1/2] Removing module @mvce-superstars/hello-world-npm...
[2/2] Regenerating lockfile and installing missing dependencies...
success Uninstalled packages.
Done in 0.06s.

and add it again (yarn add @mvce-superstars/hello-world-npm):

yarn add v1.22.4
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ @mvce-superstars/[email protected]
info All dependencies
└─ @mvce-superstars/[email protected]
Done in 1.08s.

Sources:

Sign up to request clarification or add additional context in comments.

10 Comments

perhaps, although I highly doubt it. I was able to solve it with Yarn2, and using the new yarnrc.yml file pretty easily (with no other changes) suggesting that it is a Yarn problem. However, your answer is absolutely fantastic, and will likely be helpful to others, you clearly put effort into this and testing it, so you definitely deserve the accepted answer to this. But if this doesn't work for some one else as well. Try upgrading to Yarn 2 :)
@MLyck Great. I have updated my answer with the results of using yarn v2.
I couldn't understand this... where's the authToken?
@geoidesic you create the token in Github. See the link
@smac89 yes, I understand that. I mean that authToken doesn't feature in your answer, so how to specify the token value is not clear.
|
5

You need only to use .npmrc in the root of your project with this content:

//npm.pkg.github.com/:_authToken=GITHUB_PERSONAL_TOKEN
@OWNER:registry=https://npm.pkg.github.com

Keep in mind that GITHUB_PERSONAL_TOKEN needs read:packages scope permissions in order to read the packages from your private repo.

2 Comments

Yarn does not read .npmrc. It's looking for .yarnrc.yml.
for yarn classic (v1) it does read .npmrc
5

I am adding an answer here because after a day of trying different variations of the solutions here and elsewhere, I found that my issue was something else.

My issue was that, while npm is not case sensitive with regards to package names, yarn is when it comes to authentication! 🤦‍♂️

So, using the example from this solution:

registry=https://registry.yarnpkg.com/

@GITHUB_USERNAME:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=AUTH_TOKEN
always-auth=true

I needed to ensure two things:

  1. @GITHUB_USERNAME needs to match the case that you see on github and the name the package was published under. I.e., if your username is Pickle-Rick, you need to put @Pickle-Rick:registry=https://npm.pkg.github.com, not @pickle-rick or @Pickle-rick.

  2. You need to match this casing in your package.json or your yarn add command - whichever you are using. For example:

    "@Pickle-Rick/schwifty": "^1.0.0" in package.json or yarn add @Pickle-Rick/schwifty.

I found this solution by digging through yarn github issues.

2 Comments

You need to match this casing thank you for this!! I've been trying for the past hour and was doing everything per the examples I found online, but no one mentioned the casing. NPM works with lowercase even though the username is camelcase
Thanks! It was not obvious to me from anything I read elsewhere that I need both lines: ``` @GITHUB_USERNAME:registry=npm.pkg.github.com //npm.pkg.github.com/:_authToken=AUTH_TOKEN ```
3

How we solved this at work

Late to the party, but just had this issue at work, specifically when using yarn as the package manager. This worked for us...

(the key was this documentation for actions/setup-node)

Context:

  • All repos/packages are stored under our github Organisation and are private
  • 1 repo which publishes a github npm package
  • 1 repo which consumes the package
  • Yarn v4.3.1

Solution for yarn install locally:

  • all devs create a .yarnrc.yml in their home folder. Eg. ~/.yarnrc.yml
  • each dev creates a personal access token on github to use in this local yarn config
# ~/.yarnrc.yml
npmRegistryServer: https://registry.yarnpkg.com

npmScopes: {
  Octopus-Moneycoach: {
    npmRegistryServer: https://npm.pkg.github.com,
    npmAlwaysAuth: true,
    npmAuthToken: PERSONAL_ACCESS_TOKEN,
  },
}

Solution for yarn install in Github workflow:

  • repo/package set up to allow read access to the consuming repo
  • Consuming repo has step in workflow .yml before the step containing yarn install. Step points to a custom composite action in repo under .github/actions/setup-yarnrc/action.yml
# .github/actions/setup-yarnrc/action.yml

# See https://github.com/actions/setup-node/blob/main/docs/advanced-usage.md#yarn2-configuration

name: "Setup .yarnrc.yml"
description: "Creates the .yarnrc.yml file needed to authenticate with the GitHub npm registry."
inputs:
  NPM_AUTH_TOKEN:
    description: "The GitHub token to use for authentication."
    required: true
runs:
  using: "composite"
  steps:
    - name: Setup Node.js environment
      uses: actions/setup-node@v4
      with:
        node-version: 20

    - name: Setup .yarnrc.yml
      run: |
        yarn config set npmScopes.<GITHUB_ORG_NAME>.npmRegistryServer "https://npm.pkg.github.com"
        yarn config set npmScopes.<GITHUB_ORG_NAME>.npmAlwaysAuth true
        yarn config set npmScopes.<GITHUB_ORG_NAME>.npmAuthToken $NPM_AUTH_TOKEN
      shell: bash
      env:
        NPM_AUTH_TOKEN: ${{ inputs.NPM_AUTH_TOKEN }}

With this composite action created, you can call it from your workflow. For example, our workflow that runs on every PR looks like this:

# .github/workflows/pull-request-triage.yml

name: Pull Request Triage

on:
  pull_request:
    branches:
      - develop
    types: [opened, reopened, synchronize, ready_for_review]

jobs:
  pr-triage:
    name: PR triage
    runs-on: ubuntu-latest
    if: ${{ !github.event.pull_request.draft }}
    steps:
      - name: Check out code
        uses: actions/checkout@v4

      # -----------------------------------------------
      # This step calls the composite action 
      # to create the `.yarnrc.yml` in the workflow

      - name: Setup .yarnrc.yml
        uses: ./.github/actions/setup-yarnrc
        with:
          NPM_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      # -----------------------------------------------

      - name: Cache node modules
        uses: actions/cache@v4
        with:
          path: node_modules
          key: yarn-deps-${{ hashFiles('yarn.lock') }}
          restore-keys: |
            yarn-deps-${{ hashFiles('yarn.lock') }}

      - name: Install dependencies
        run: yarn install --immutable

      - name: Lint
        run: yarn lint

      - name: Test
        run: yarn test

Comments

0

This is what worked for me using Yarn V1

# .npmrc
@vesato:registry=https://gitlab.com/api/v4/projects/[xx]/packages/npm/
//gitlab.com/api/v4/projects/[xx]/packages/npm/:_authToken=${NPM_TOKEN}

And this is what worked after changing to Yarn V2

# .yarnrc.yml

nodeLinker: pnp

npmScopes:
  "vesato":
    npmAlwaysAuth: true
    npmRegistryServer: https://gitlab.com/api/v4/projects/[xx]/packages/npm/
    npmAuthToken: "${NPM_TOKEN}"

yarnPath: .yarn/releases/yarn-3.2.2.cjs

Finally use the import as below.

import {x} from "@vesato/libraryname"

Comments

0

For Gitlab I used:

npmScopes:
  "<namespace>":
    npmRegistryServer: "https://<server>/api/v4/packages/npm/"

npmRegistries:
  //<server>/api/v4/packages/npm:
    npmAlwaysAuth: true
    npmAuthToken: ${GITLAB_AUTH_TOKEN}

To allow committing the file, it's possible to store the authentication token in an environment variable.

Comments

0

The safe way for Yarn 4, with token stored in your user directory:

  1. Add scope information to your package .yarnrc.yml

    npmScopes:
      your_scope:
        npmRegistryServer: "https://npm.pkg.github.com"
        npmAlwaysAuth: true
    
  2. Execute

    yarn npm login --scope your_scope
    

your_scope in both cases is without @

To validate, check if there is ~/.yarnrc.yml with the token.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.