Use Private NPM Registry and Packages

When building large-scale NodeJS and front-end projects, it’s necessary to use private NPM registry to share private packages across different projects and team members. This post shows the essential parts of how to build the infrastructure and set up the workflow to use them.

Set up the registry

First of all, you need a private registry. You can choose to use a paid account in npmjs.org or use other paid services. Here I used the open-source solution Verdaccio.

Verdaccio has an official Docker image. So I just deploy the Docker image to Amazon ECS and get it running very quickly.

Mark a package as private

Private packages should be scoped. For example, we should use @mycompany/mypackage as the package name. @mycompany is the scope.

The package.json should be updated to specify the registry to publish the package.

1
2
3
"publishConfig": {
"registry": "http://npm.mycompany.com"
}

Publish

Since the private registry is already specifies in the package.json, we can use npm publish to publish it. Or we can use npm publish --registry http://npm.mycompany.com to specify the registry explicitly.

Work with CI server

To work with CI server, we need to create the file .npmrc for the build process. After using npm login to login to the registry, there is a file .npmrc that contains the authentication token.

1
//npm.mycompany.com/:_authToken="<token>"

We can use echo to generate this file during the build process and pass the token as an environment variable.

1
echo '//npm.mycompany.com/:_authToken="${NPM_TOKEN}"' > ~/.npmrc

Use private packages

To use published private packages, we need to associate the scope with the registry. This can be done when login to private registry.

1
npm login --registry=http://npm.mycompany.com --scope=@mycompany

Or this can be done using npm config.

1
npm config set @mycompany:registry npm.mycompany.com

Once the scope has been configured to associate with the registry, we can remove the registry configuration in the package.json.

After this configuration, we can simply using npm install or yarn to install scoped private packages.

Comments