---
title: "Access Private NPM Packages in CI/CD Jobs"
date: 2022-01-13T16:04:39.000Z
author: Z.SHINCHVEN
tags: [NPM Authentication, CI/CD]
canonical: https://atlassc.net/2022/01/14/access-private-npm-packages-in-ci-cd-jobs
---
NPM packages in private NPM registries can be accessed via `NPM_TOKEN` authentication in CI/CD jobs. Here's the [official guide](https://docs.npmjs.com/using-private-packages-in-a-ci-cd-workflow) 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:

```bash
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:

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

## Explanation

### Scope Private Packages

[Scopes](https://docs.npmjs.com/cli/v8/using-npm/scope) 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.

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

### Registry Authentication

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

```bash
echo "//<NPM_REGISTRY_URL_WITHOUT_TRANSPORT_PROTOCOL>/:_authToken=${NPM_TOKEN}" >> ~/.npmrc
```

* Please replace NPM_REGISTRY_URL_WITHOUT_TRANSPORT_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](/2022/01/13/gitlab-runner-environment-variables/).

### Generating a NPM Access Token

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

```bash
npm login --registry=<NPM_REGISTRY_URL>
```

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

```bash
cat ~/.npmrc
```
