I\'m trying to follow a tutorial and it says:
There are a few ways to load credentials.
- Loaded from environment variables,
For windows users this Stack Overflow question and top answer is quite useful on how to set environement variables via the command line
How can i set NODE_ENV=production in Windows?
I highly recommend looking into the dotenv package.
https://github.com/motdotla/dotenv
It's kind of similar to the library suggested within the answer from @Benxamin, but it's a lot cleaner and doesn't require any bash scripts. Also worth noting that the code base is popular and well maintained.
Basically you need a .env file (which I highly recommend be ignored from your git/mercurial/etc):
FOO=bar
BAZ=bob
Then in your application entry file put the following line in as early as possible:
require('dotenv').config();
Boom. Done. 'process.env' will now contain the variables above:
console.log(process.env.FOO);
// bar
The '.env' file isn't required so you don't need to worry about your app falling over in it's absence.
Just provide the env values on command line
USER_ID='abc' USER_KEY='def' node app.js
Like ctrlplusb said, I recommend you to use the package dotenv
, but another way to do this is creating a js file and requiring it on the first line of your app server.
env.js:
process.env.VAR1="Some value"
process.env.VAR2="Another Value"
app.js:
require('env')
console.log(process.env.VAR1) // Some value
It depends on your operating system and your shell
On linux with the shell bash, you create environment variables like this(in the console):
export FOO=bar
For more information on environment variables on ubuntu (for example):
Environment variables on ubuntu
Make your life easier with dotenv-webpack. Simply install it npm install dotenv-webpack --save-dev
, then create an .env
file in your application's root (remember to add this to .gitignore
before you git push
). Open this file, and set some environmental variables there, like for example:
ENV_VAR_1=1234
ENV_VAR_2=abcd
ENV_VAR_3=1234abcd
Now, in your webpack config add:
const Dotenv = require('dotenv-webpack');
const webpackConfig = {
node: { global: true, fs: 'empty' }, // Fix: "Uncaught ReferenceError: global is not defined", and "Can't resolve 'fs'".
output: {
libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
},
plugins: [new Dotenv()]
};
module.exports = webpackConfig; // Export all custom Webpack configs.
Only const Dotenv = require('dotenv-webpack');
, plugins: [new Dotenv()]
, and of course module.exports = webpackConfig; // Export all custom Webpack configs.
are required. However, in some scenarios you might get some errors. For these you have the solution as well implying how you can fix certain error.
Now, wherever you want you can simply use process.env.ENV_VAR_1
, process.env.ENV_VAR_2
, process.env.ENV_VAR_3
in your application.