avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

Access Private NPM Packages in CI/CD Jobs

Thu Jan 13 2022

NPM packages in private NPM registries can be accessed via NPM_TOKEN authentication in CI/CD jobs. Here's the official guide on how to do it.

And I also want to make a digest note on that.

In Short

Assuming your conditions are like below:

  • Scope: @my-scope
  • Registry: https://registry.example.com
  • NPM Token: 7151942c-7451-11ec-90d6-0242ac120003

Here what you do in your CI/CD script:

echo "@my-scope:registry=https://registry.example.com" >> ~/.npmrc
echo "//registry.example.com/:_authToken=${NPM_TOKEN}" >> ~/.npmrc

After it's done, ~/.npmrc file in your CI/CD container should be something like this:

@my-scope:registry=https//registry.example.com/
//registry.example.com/:_authToken=7151942c-7451-11ec-90d6-0242ac120003

Explanation

Scope Private Packages

Scopes are a way of grouping related packages together. Assigning a registry url to a scope in .npmrc file can tell package managers to look for packages in the scope from the specified registry.

echo "@<SCOPE>:registry=<NPM_REGISTRY_URL>" >> ~/.npmrc

`

Registry Authentication

We can set up authentication for multiple specified registries in .npmrc file.

echo "//<NPM_REGISTRY_URL_WITHOUT_TRANSPORT_PROTOCOL>/:_authToken=${NPM_TOKEN}" >> ~/.npmrc
  • Please replace NPMREGISTRYURLWITHOUTTRANSPORT_PROTOCOL with something like registry.example.com, DO NOT prefix it with http:// or https://.
  • In CI/CD jobs, ${NPM_TOKEN} should be passed as an environment variable.

Generating a NPM Access Token

Different registries can have different ways of generating authentication tokens, the common way is to use npm login command.

npm login --registry=<NPM_REGISTRY_URL>

Once it's done, open the ~/.npmrc file to find the _authToken value.

cat ~/.npmrc