Using a private npm package registry

Installing packages via npm or yarn is part of the day to day business in web development and everybody can publish their own package on the public npm registry. But what if you want to publish and reuse your own package without making it available to the world? We were facing this issue when we wanted to reuse components from one package in multiple projects.

This is where a private npm registry comes in handy. You can publish private packages directly at npm (with a paid user account) or host them at gitlab, which is what we did since we run our own gitlab. So how does this work?

Imagine we have a group in gitlab called Foo. Inside Foo, there are multiple repositories, including FooBarComponents, FooWebsite, BazTools and so on. Now we want to make the FooBarComponents available as npm package to FooWebsite, BazTools etc. Follow these steps:

In the FooBarComponents Repository

  1. You might need to enable the package repository in the repository settings under permissions
  2. Generate an access token, either a deploy token or personal access token, read more here
  3. Define the scope of your package: In our case, this is the name of our group, Foo. So in the package.json of FooBarComponents, change the name from FooBarComponents to @Foo/FooBarComponents
  4. Define the endpoint for your scope. This tells npm where to publish packages in this scope: npm config set -- @Foo:registry https://gitlab.example.com/api/v4/projects/<yourProjectId>/packages/npm/
  5. Tell npm to use your token generated in step 2: npm config set -- '//gitlab.example.com/api/v4/projects/<yourProjectId>/packages/npm/:_authToken' "<your-secret-token>"
  6. Publish your package with npm publish

Your package now lives in your gitlab's package repository. To make your life easier you can also add a step in your projects CI which automatically publishes new versions of the package.

Now, in the repository where you want to use the package, repeat the steps 4 & 5 to register the endpoint and add authentication, and then install your package with npm i @Foo/FooBarComponent.

Happy Publishing!