Using Private NPM Packages in Netlify

This article does not cover how to create an NPM package, how to make a package private, or how to host your app on Netlify. This article covers how to give Netlify access to your private packages so it can build and deploy your app properly.

NPM Token

First we need to create an NPM auth token that basically gives auth to whoever has it to read or write on your behalf.You can use the CLI to generate the auth token:

npm token create --read-only

Otherwise you just have to login to npmjs.com and then under your account you can see all the tokens you’ve issued. Check out the official guide for more detailed instructions.

Make sure to give your token read only access, the less tokens you have with publish permissions the better.

Netlify

Now that you have the token, it's time to head over to Netlify to give them the token. Login to Netlify and go to your app’s build settings, you should find a section for adding environment variables there. You’ll be able to assign a key and a value, so for the key let's call it NPM_TOKEN and set the value to be the auth token you just generated. For more details on adding environment variables check out Netlify’s docs.

.npmrc

Great, now we’ve given Netlify our secret auth token, the last step is to tell it how to use it when building it.

NPM allows you to set literally tens of settings about how to interact with the package registry using a .npmrc file in your project’s root directory. If you want to geek out on all the different options check out the full list, but the one we want customizes the url of the registry, and the cool thing is we can use environment variables (It's a good idea to store the token as an environment variable as it's bad practice and insecure to commit your tokens to your repository).

So this concept applies to any registry that is hosting your private package, if you're not hosting it through npmjs.com, then you'll need to check what format the url should be first. If you are hosting on npmjs.com, then you'll add the following line to your .npmrc file:

registry=//registry.npmjs.org/:_authToken=${NPM_TOKEN}

Let’s say you have a scope of various packages hosted on a private registry, then you can specify a different registry for that entire scope like this.

@scopenamehere:registry=//registry.npmjs.org/:_authToken=${NPM_TOKEN}

Boom. Now, we push this new change and Netlify will be able to download our package to build it properly, and since we stored the token in an environment variable, we don’t have to worry about anyone stealing it.