How to use $npm_config_ in package.json?

Viewed 2567

I'm using create-react-app for my React project (ejected), and I've configured a proxy in package.json. But I don't want to have my credentials committed in this file. So I've added to npm using npm config set my_user xxxx. I can see them in my ~/.npmrc, too.

"proxy": {
  "/api/v3/": {
    "target": "https://ourstagingserver.nl/",
    "changeOrigin": true,
    "ssl": false,
    "secure": false,
    "headers": {
      "username": "$npm_config_my_user",
      "password": "$npm_config_my_pass"
    }
  },

This doesn't work. The username and password are not used in the proxy requests.

But if I add this to "scripts":

"hello": "echo $npm_config_my_user $npm_config_my_pass

and run npm run hello, both are echoed...

Any ideas? Is this supposed to work or am I doing it wrong?

Thx! Gijs

1 Answers

I didn't figure out the use of $npm_config_ variables for this purpose but I did solve the issue of using ENV variables for the proxy in create-react-app:

In scripts/start.js (line 62, below const proxySetting = require(paths.appPackageJson).proxy), add this:

proxySetting[Object.keys(proxySetting)[0]].headers.username = process.env.PROXY_USERNAME;
proxySetting[Object.keys(proxySetting)[0]].headers.password = process.env.PROXY_PASSWORD;

or you could loop over the objects in proxySetting and set the credentials for every object in there if you have multiple API's to proxy to:

Object.keys(proxySetting).forEach(function(proxy) {
  proxySetting[proxy].headers.username = process.env.PROXY_USERNAME;
  proxySetting[proxy].headers.password = process.env.PROXY_PASSWORD;
});

Note: scripts/start.js is a file that's generated by create-react-app

Related