dotenv allows you to store sensitive data variables locally (Secret Keys, etc), without having to include them directly in your app files.
This is based off of dotenv-webpack’s NPM package.
You first want to install dotenv-webpack via your terminal:
npm install dotenv-webpack --save
Then create a file in the root of your directory .env
and add your secret keys or whatever it is you want to hide like this.
SECRET_KEY_EXAMPLE = '3213213232132132123132adassdasdsd';
Now make sure to add .env
to your .gitignore
file so that it doesn’t get deployed to Git.
# .gitignore
.env # Add to .gitignore file
node_modules
Then add this plugin to your webpack.config.js
file.
// webpack.config.js
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
fs
or dotenv-webpack
that gives you this error: Error: Can't resolve 'fs' in
. Nevertheless, I've included the work-around below.
(Work-around): Also include this to your webpack.config.js
file if getting the aforementioned error:
module.exports = {
// Add
node: {
fs: 'empty'
},
...
...
...
In your main project folder ie index.js
, add this line of code to require dotenv.
require('dotenv').config(); // See Blurb/Alert above
And you can test to see that it’s working by logging it to your console like so:
console.log(process.env.SECRET_KEY_EXAMPLE);
Please let me know in the comments that everything is working for you guys. I noticed the up-votes on the first comment that it wasn’t working, but I think I found the culprit and posted the fix above, but to be certain I’d appreciate it if you could let me know…
Thanks,
-Colin.