Managing NPM Tokens when Deploying to Netlify

02 May 19 | Web Development

Deploying a static site to Netlify is extremely easy, fast, and cheap. However, managing environmental variables, especially for npm, can get a little tricky. If you have npm packages that require token's or authentication to fetch you're most likely going to have to give Netlify that information, without adding it your repository. This is made tricker by the fact that the npm docs show a way, which actually does not work for all operating systems, so here is a quick example that's tried and tested.

Add an .npmrc file to your project root with your npm configuration values, but replace the sensitive information with $VARIABLE_NAME. (Note: this differs from the docs that say you should place the variables name between two curly brackets. ${VARIABLE_NAME})

The following is my .npmrc for this site.

@fortawesome:registry=https://npm.fontawesome.com/
//npm.fontawesome.com/:_authToken=$FONTAWESOME_TOKEN

Then set your env variables as you usually do in your .env file, this version will be used for local development. Do not commit this file, add it to your .gitignore.

Before you push this branch to GitHub for Netlify to re-build, add the same environmental variables to your Netlify site's settings.

And voila, your env variables will be loaded, npm configuration set, and you will be able to deploy projects that contain private packages to Netlify.