Managing environment variables in Node.js

export AWS_SECRET_ACCESS_KEY=fooexport AWS_ACCESS_KEY_ID=bar
var secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
var accessKeyId = process.env.AWS_ACCESS_KEY_ID;

The solution: Local environment variables

Yep, environment variables which only exist in the scope of a certain project.

  • A way to read local environment variables
  • A setup script
  • An ignore rule for our environment file

The setup

We first install the package:

npm install dotenv --save
AWS_SECRET_KEY=fake_secret
AWS_ACCESS_KEY_ID=fake_key_id
'use strict';
fs = require('fs');
fs.createReadStream('.sample-env')
.pipe(fs.createWriteStream('.env'));
node setup.js
.env
AWS_SECRET_KEY=real_secret
AWS_ACCESS_KEY_ID=real_key_id
var dotenv = require('dotenv');// There's no need to check if .env exists, dotenv will check this // for you. It will show a small warning which can be disabled when // using this in production.
dotenv.load();

Remember, this is for your Development environment, not Production

It is important to remember that this setup should only be used for development.
For production you should still set your environment variables in the standard way.

That’s it.

Hope this helps you as it has helped me, feel free to comment your thoughts on this approach.

--

--

Founder of www.gambitstudio.com, a small, super efficient, no-bullshit software development agency.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rafael Vidaurre

Rafael Vidaurre

Founder of www.gambitstudio.com, a small, super efficient, no-bullshit software development agency.