I am trying to set and retrieve node app process.env vars using package.json, so by researching the issue, I've found an example to set / retrieve process.env through the 'config' section, so I added a new config section as shown below :
"config" : { "var1" : "test", "var2" : "test2", "var3" : "test3" },
But I couldn't access any of the above vars from server.js using for example:
console.log(process.env.npm_package_config_var1);
So I was wondering how I can set / retrieve process.env var using package.json? Thanks
*I am using npm 4.4.1, node 7.4.0 and I run the app using (npm run dev)
Environment variables are something that your programs get at runtime, not something stored in a config - unless you use something like dotenv, see: but this is using the .env file, not package.json. Show activity on this post. You cannot just set environment variables in package.json. Yes you can.
but this is using the .env file, not package.json. Show activity on this post. You cannot just set environment variables in package.json. Yes you can. You may try out node -p process.env as your npm script to inspect your env variable. And ensure that nothing else overwrites your values. Here is another example which works for me.
Open your package.json file and set the environment variables inside script command like this. Now, you can access the environment variables inside your app using process.env.variable-name.
First, we need to install a new package called cross-env which helps us to set environment variables across all platforms (like windows, mac, linux, etc). Open your package.json file and set the environment variables inside script command like this. Now, you can access the environment variables inside your app using process.env.variable-name.
You cannot just set environment variables in package.json.
You can set them in your script sections using:
"scripts": {
"start": "ENV_VAR=abc node app.js",
},
or:
"scripts": {
"start": "cross-env ENV_VAR=abc node app.js",
},
using the cross-env module. See:
Environment variables are something that your programs get at runtime, not something stored in a config - unless you use something like dotenv, see:
but this is using the .env
file, not package.json.
You cannot just set environment variables in package.json.
Yes you can.
You may try out node -p process.env
as your npm script to inspect your env variable. And ensure that nothing else overwrites your values. Here is another example which works for me.
I don't really understand, what are you trying to do.
But if you want to retrieve env variables you have to do define your dev script in your package.json
like this : NODE_ENV=dev node index.js
Then fetch your env with : process.env.NODE_ENV
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With