62

I need a module in my project to download a private npm package. To accomplish this, I am using a .npmrc file to supply a read-only token needed to download the package. To keep the token supplied by npm out of the file, I wish to add it as an environment variable and let it expand in the file. E.g:

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

I can't figure out how to get that NPM_TOKEN added to the env before it is referenced for the install. I tried using an npm preinstall script:

"preinstall": "NPM_READ_ONLY_TOKEN=my_token_goes_here_foo_bar"**

But I still get the same error:

Error: Failed to replace env in config: ${NPM_READ_ONLY_TOKEN}

I tried testing with an echo command to see if preinstall runs before the .npmrc variable expansion, but it apparently does not. I would get the error and not see my echo log. I seem to be missing something here.

I'm aware that putting my token in package.json defeats the purpose of pulling the token out of the .npmrc file. I'm actually using a service that provides env config services that I would use to run a command and get the needed token. E.g. TOKEN=config_service_value.

skwny
  • 2,930
  • 4
  • 25
  • 45

3 Answers3

46

You can add the environment variable to your .bashrc or other startup shell file.

export NPM_TOKEN=my_token_goes_here_foo_bar

jonathanhculver
  • 655
  • 6
  • 8
  • 41
    For those in a hurry like me that do not read the question thoroughly, an environment variable is not sufficient, the .npmrc file is also required, containing `//registry.npmjs.org/:_authToken=${NPM_TOKEN}` – Gudlaugur Egilsson Jul 11 '19 at 14:43
  • 4
    THE RIGHT ANSWER - I tried ~250 different articles & answers within three days. https://stackoverflow.com/a/61666885/3748178 – Salathiel Genese Sep 05 '20 at 20:33
  • this doesn't work for me and I do have the env vars in my .bashrc before nvm is loaded. – Brad Nov 23 '20 at 05:08
  • 1
    @SalathielGenèse same here! Thanks for pointing me to the correct answer!!! – chriszichrisz Apr 14 '21 at 12:21
4

Here is how one would set an environment variable in Powershell (Windows 10):

$env:ENV_VARIABLE = 'Value of my environment variable'

And here is the reference link for further study

Anindya Dey
  • 825
  • 1
  • 8
  • 18
4

If you are using zsh for your terminal. You should put the environment variable in the .zshenv file.

echo "export NPM_TOKEN=token_goes_here" >> ~/.zshenv

Then you have to restart your terminal and then try echo $NPM_TOKEN, you should be seeing the value of the environment variable.

samuellawrentz
  • 1,662
  • 11
  • 23