• Stars
    star
    201
  • Rank 194,491 (Top 4 %)
  • Language
    JavaScript
  • License
    GNU General Publi...
  • Created about 9 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ“Learn how to use Environment Variables to keep your passwords and API keys secret. πŸ”

Learn Environment Variables HitCount

Learn how to use Environment Variables keep your secret keys safe & secure!

Why? 🀷

Avoid (accidentally) committing (exposing) your private keys, passwords or other sensitive details
(by hard-coding in them in your script) to GitHub by storing them as environment variables.

Accidentally pushing API keys to GitHub can be an Expensive/Stressful Lesson: https://www.quora.com/My-AWS-account-was-hacked-and-I-have-a-50-000-bill-how-can-I-reduce-the-amount-I-need-to-pay

What? πŸ’­

An environment variable is a KEY=value pair that is stored on the local system where your code/app is being run and is accessible from within your code.

If you are new to "back end" development, you may not have encountered environment variables before, this quick guide will tell you all you need to know!

The Twelve-Factor App best practice recommends storing your app's configuration in the "environment", but what does that mean?

This simply means that you save any configuration both the values that are the
same everywhere you run your app and the keys that change depending on where
you are running the app, in the environment where you are running your app.

How? πŸ’»

List all the Default Environment Variables

In your terminal type: printenv and then the enter key.

You should see something like this:

{
  TERM_PROGRAM: 'Apple_Terminal',
  SHELL: '/bin/bash',
  TERM: 'xterm-256color',
  TERM_PROGRAM_VERSION: '343.7',
  USER: 'n',
  PWD: '/Users/n/code/learn-environment-variables',
  LANG: 'en_GB.UTF-8',
  _system_arch: 'x86_64',
  _system_name: 'OSX',
  _: '/usr/local/bin/node'
}

This is a list of all the variables defined in your environment, in this case we are running printenv on a Mac using the "Terminal" app,
if you are on Linux/Unix using Bash/etc. you will see something slightly different.

Log the list of environment variables available to node.js in process.env

Node.js gives you access to the variables defined in your environment in the process.env global object.

Create a file called printenv.js and type/paste the following line in it:

console.log(process.env);

Run this script in your terminal:

node printenv.js

Adding Variables to your Environment

There are 3 ways to add variables to the environment where your app is running.

1. Command-Line Arguments

When you run your node program/app you can include settings as environment variables for example, try running the following:

PORT=1337 node printenv.js

Notice how the PORT variable is the first element displayed in the console? You are now able to access the PORT value in your node.js script by reference: process.env.PORT

including your config in the command you use to run your script/app gets cumursome when you have lots of API Keys or Databases ...

2. Export the Variable to your Environment

An improvement on this command-line arguments is to export the variable in your terminal:

Type/paste this in your terminal window and tap enter:

export HELLO=WORLD

Now printenv or node printenv.js to see it printed! the HELLO key is now available in the process.env object try adding the following line to your printenv.js file:

console.log(">> Hello", process.env.HELLO);

Now run it in your terminal:

node printenv.js

What do you see?

>> Hello WORLD

Exporting your keys to your environment using export MY_VAR=HAI works but if you use a terminal that does not save your variables across sessions, (e.g. if you close your terminal window!) you will have to keep exporting them!

Thankfully there's a 3rd (easier) way: https://github.com/dwyl/env2

3. Use a .env file locally which you can .gitignore

The way we prefer to manage our Environment Variables on our development machines is using a .env file which gets loaded into our app once and adds any entries in the .env file to the process.env (global object).

We wrote the env2 node.js module to load configuration from a .env or .json file.

Loading your environment variables from a .env file is as easy as "ABC"!

A. Create your .env file

Create a .env file in the root of your project and insert your key/value pairs in the following format of KEY=VALUE:

DB_HOST=127.0.0.1
DB_PORT=9200
DB_USER=TheSpecial
DB_PASS=EverythingIsAwesome
B. Install env2 and save it to your package.json

Install the env2 module from NPM and save it as a Dependency in your package.json file:

npm install env2 --save
C. Invoke env2 and use the variable in your script

Loading your configuration is a 1-line call to node.js's require method which loads env2 and invokes it with your .env file as the argument:

require('env2')('.env');    // loads all entries into process.env

console.log(process.env.DB_HOST); // "127.0.0.1"

Now you can access any of the entries in your .env file as a key in the process.env Object e.g: process.env.PORT is 9200 (in our example above).

D. Add .env to your .gitignore file!
echo .env >> .gitignore

This ensures that the .env is not "tracked" in .git and thus will not be public on GitHub. i.e only visible on your local machine.
If you are new/rusty on using .gitignore file to omit files/folders from your Git/GitHub repo read: http://git-scm.com/docs/gitignore

1env2 solves the problem of loading config files, we recommend using env2 because the code is clean, tested & documented, but there are other solutions to this problem on NPM you can chose from depending on your needs. But if env2 does cover your specific use-case, please tell us about it, we always love helping to solve problems and enhance our modules to be more useful to people!

Environment Variable Naming Convention

The Google Shell Style Guide (naming convention) states: All caps, separated with underscores so this is Good:

export DATABASE_HOST=localhost

Whereas this is Bad:

export databaseHost=localhost

see: https://google.github.io/styleguide/shell.xml#Constants_and_Environment_Variable_Names

Removing an Environment Variable

If you have exported an environment variable in your terminal, e.g:

export PORT=8000

You can unset (delete) it by running:

unset PORT

Now the PORT environment variable will no longer be set.


Using Environment Variables with Travis-CI! Build Status

If you are new to Travis-CI check out our introductory tutorial (for complete beginners): https://github.com/dwyl/learn-travis

There are two ways of telling Travis-CI about your environment variables:

1. Include Environment Variables in your .travis.yml file

The easiest and most explicit way of listing your environment variables is to add them to your .travis.yml file:

language: node_js
node_js:
  - 6
env:
- MY_VAR=EverythignIsAwesome
- NODE_ENV=TEST

The interesting part is the env: key where you can then list your environment variables and their corresponding values.

2. Add environment Variables in the Web Interface

The other way of telling Travis-CI your environment variable(s) is to add them in the web-base user-interface (Web UI) in your project's settings page:

add travis-ci environment variables Web UI

Notice how in if you add your environment variables in the the Travis Web UI they are hidden (from the build log) by default. This does not prevent you from accidentally console.log them and exposing a key/passord. So take care when console.logging ...!

Secure (Encrypted) Environment Variables

If you are storing sensitive information (like API Keys or Database Passwords) for use in your node app, the best way is to use the travis ruby gem to encrypt your keys:

You will need to have ruby installed on your computer, if you don't already have this, we recommend installing it with RVM:

\curl -L https://get.rvm.io | bash -s stable --ruby
rvm install current && rvm use current

Once you have installed ruby you can install the travis ruby gem:

gem install travis

With the gem installed, you encrypt your variable by running the command in your terminal (ensure you are in the working directory of your project)

travis encrypt MY_SECRET=super_secret

Type yes to confirm you are your project, you should now see your encrypted variable:

learn-travis-encrypted-variable

Paste this in your .travis.yml file and commit it to GitHub!


Environment Variables on Heroku

Visit your apps dashboard on heroku and click on the app you want to add an environment variable to:

Go to Settings and Click Reveal Config Vars to view the Config Vars: heroku reveal config vars

Next, click on edit and and add your desired key/value pair:

add your env vars

That's all there is to it!

Research & Background Reading

Thanks!

Thanks for learning about Environment Variables with us!
If you have any questions, please ask!!
Please ⭐ this repo to help spread the word!

If you are using environment variables in a way not mentioned in this readme, or have a better way of managing them or any other ideas or suggestions for improvements please tell us!!

More Repositories

1

english-words

πŸ“ A text file containing 479k English words for all your dictionary/word-based projects e.g: auto-completion / autosuggestion
Python
9,337
star
2

learn-json-web-tokens

πŸ” Learn how to use JSON Web Token (JWT) to secure your next Web App! (Tutorial/Example with Tests!!)
JavaScript
4,178
star
3

learn-to-send-email-via-google-script-html-no-server

πŸ“§ An Example of using an HTML form (e.g: "Contact Us" on a website) to send Email without a Backend Server (using a Google Script) perfect for static websites that need to collect data.
HTML
3,140
star
4

repo-badges

⭐ Use repo badges (build passing, coverage, etc) in your readme/markdown file to signal code quality in a project.
HTML
2,831
star
5

learn-tdd

βœ… A brief introduction to Test Driven Development (TDD) in JavaScript (Complete Beginner's Step-by-Step Tutorial)
JavaScript
2,698
star
6

start-here

πŸ’‘ A Quick-start Guide for People who want to dwyl ❀️ βœ…
1,734
star
7

learn-elixir

πŸ’§ Learn the Elixir programming language to build functional, fast, scalable and maintainable web applications!
Elixir
1,611
star
8

learn-travis

😎 A quick Travis CI (Continuous Integration) Tutorial for Node.js developers
JavaScript
1,251
star
9

Javascript-the-Good-Parts-notes

πŸ“– Notes on the seminal "JavaScript the Good Parts: by Douglas Crockford
1,193
star
10

aws-sdk-mock

🌈 AWSomocks for Javascript/Node.js aws-sdk tested, documented & maintained. Contributions welcome!
TypeScript
1,113
star
11

learn-aws-lambda

✨ Learn how to use AWS Lambda to easily create infinitely scalable web services
JavaScript
1,035
star
12

book

πŸ“— Our Book on Full-Stack Web Application Development covering User Experience (UX) Design, Mobile/Offline/Security First, Progressive Enhancement, Continuous Integration/Deployment, Testing (UX/TDD/BDD), Performance-Driven-Development and much more!
Rust
818
star
13

hapi-auth-jwt2

πŸ”’ Secure Hapi.js authentication plugin using JSON Web Tokens (JWT) in Headers, URL or Cookies
JavaScript
795
star
14

learn-hapi

β˜€οΈ Learn to use Hapi.js (Node.js) web framework to build scalable apps in less time
HTML
794
star
15

phoenix-chat-example

πŸ’¬ The Step-by-Step Beginners Tutorial for Building, Testing & Deploying a Chat app in Phoenix 1.7 [Latest] πŸš€
Elixir
760
star
16

learn-tachyons

😍 Learn how to use Tachyons to craft beautiful, responsive and fast UI with functional CSS!
HTML
673
star
17

learn-phoenix-framework

πŸ”₯ Phoenix is the web framework without compromise on speed, reliability or maintainability! Don't settle for less. πŸš€
Elixir
650
star
18

javascript-todo-list-tutorial

βœ… A step-by-step complete beginner example/tutorial for building a Todo List App (TodoMVC) from scratch in JavaScript following Test Driven Development (TDD) best practice. 🌱
JavaScript
623
star
19

learn-nightwatch

🌜 Learn how to use Nightwatch.js to easily & automatically test your web apps in *real* web browsers.
JavaScript
585
star
20

learn-elm

🌈 discover the beautiful programming language that makes front-end web apps a joy to build and maintain!
HTML
483
star
21

learn-redux

πŸ’₯ Comprehensive Notes for Learning (how to use) Redux to manage state in your Web/Mobile (React.js) Apps.
HTML
446
star
22

hits

πŸ“ˆ General purpose hits (page views) counter
Elixir
432
star
23

learn-devops

🚧 Learn the craft of "DevOps" (Developer Operations) to Deploy your App and Monitor it so it stays "Up"!
Shell
413
star
24

phoenix-liveview-counter-tutorial

🀯 beginners tutorial building a real time counter in Phoenix 1.7.14 + LiveView 1.0 ⚑️ Learn the fundamentals from first principals so you can make something amazing! πŸš€
Elixir
374
star
25

hapi-socketio-redis-chat-example

πŸ’¬ Real-time Chat using Hapi.js + Socket.io + Redis Pub/Sub (example with tests!!)
Elm
366
star
26

hapi-typescript-example

⚑ Hapi.Js + Typescript = Awesomeness
TypeScript
351
star
27

learn-istanbul

🏁 Learn how to use the Istanbul JavaScript Code Coverage Tool
JavaScript
339
star
28

learn-redis

πŸ“• Need to store/access your data as fast as possible? Learn Redis! Beginners Tutorial using Node.js πŸš€
JavaScript
291
star
29

technology-stack

πŸš€ Detailed description + diagram of the Open Source Technology Stack we use for dwyl projects.
JavaScript
288
star
30

phoenix-ecto-encryption-example

πŸ” A detailed example for how to encrypt data in an Elixir (Phoenix v1.7) App before inserting into a database using Ecto Types
Elixir
274
star
31

learn-elasticsearch

πŸ” Learn how to use ElasticSearch to power a great search experience for your project/product/website.
Elixir
265
star
32

elixir-auth-google

πŸ‘€Minimalist Google OAuth Authentication for Elixir Apps. Tested, Documented & Maintained. Setup in 5 mins. πŸš€
Elixir
263
star
33

home

🏑 πŸ‘©β€πŸ’» πŸ’‘ home is where you can [learn to] build the future surrounded by like-minded creative, friendly and [intrinsically] motivated people focussed on health, fitness and making things people and the world need!
246
star
34

learn-docker

🚒 Learn how to use docker.io containers to consistently deploy your apps on any infrastructure.
Dockerfile
220
star
35

learn-elm-architecture-in-javascript

πŸ¦„ Learn how to build web apps using the Elm Architecture in "vanilla" JavaScript (step-by-step TDD tutorial)!
JavaScript
211
star
36

learn-postgresql

🐘 Learn how to use PostgreSQL and Structured Query Language (SQL) to store and query your relational data. πŸ”
JavaScript
195
star
37

learn-tape

βœ… Learn how to use Tape for JavaScript/Node.js Test Driven Development (TDD) - Ten-Minute Testing Tutorial
JavaScript
187
star
38

sendemail

πŸ’Œ Simplifies reliably sending emails from your node.js apps using AWS Simple Email Service (SES)
JavaScript
181
star
39

phoenix-todo-list-tutorial

βœ… Complete beginners tutorial building a todo list from scratch in Phoenix 1.7 (latest)
Elixir
171
star
40

quotes

πŸ’¬ a curated list of quotes that inspire action + code that returns quotes by tag/author/etc. πŸ’‘
Elixir
163
star
41

learn-heroku

🏁 Learn how to deploy your web application to Heroku from scratch step-by-step in 7 minutes!
Python
153
star
42

decache

:shipit: Delete Cached node_modules useful when you need to "un-require" during testing for a fresh state.
JavaScript
151
star
43

learn-chrome-extensions

🌐 Discover how to build and deploy a Google Chrome Extension for your Project!
139
star
44

labels

🏷 Sync GitHub Labels from any Source to Target Repositories for Consistency across all your projects!
Elixir
138
star
45

learn-ab-and-multivariate-testing

πŸ†Ž Tutorial on A/B and multivariate testing βœ”οΈ
137
star
46

ISO-27001-2013-information-technology-security

πŸ” Probably the most boring-but-necessary repo on GitHub. If you care about the security/privacy of your data...! βœ…
136
star
47

auth

πŸšͺ πŸ” UX-focussed Turnkey Authentication Solution for Web Apps/APIs (Documented, Tested & Maintained)
Elixir
135
star
48

web-form-to-google-sheet

A simple example of sending data from an ordinary web form straight to a Google Spreadsheet without a server.
HTML
133
star
49

app

Clear your mind. Organise your life. Ignore distractions. Focus on what matters.
Dart
133
star
50

phoenix-liveview-chat-example

πŸ’¬ Step-by-step tutorial creates a Chat App using Phoenix LiveView including Presence, Authentication and Style with Tailwind CSS
Elixir
130
star
51

learn-circleci

βœ… A quick intro to Circle CI (Continuous Integration) for JavaScript developers.
121
star
52

learn-regex

⁉️ A simple REGular EXpression tutorial in JavaScript
120
star
53

learn-react

"The possibilities are numerous once we decide to act and not react." ~ George Bernard Shaw
HTML
108
star
54

learn-aws-iot

πŸ’‘ Learn how to use Amazon Web Services Internet of Things (IoT) service to build connected applications.
JavaScript
101
star
55

env2

πŸ’» Simple environment variable (from config file) loader for your node.js app
JavaScript
100
star
56

how-to-choose-a-database

How to choose the right dabase
97
star
57

flutter-todo-list-tutorial

βœ… A detailed example/tutorial building a cross-platform Todo List App using Flutter πŸ¦‹
Dart
91
star
58

imgup

πŸŒ… Effortless image uploads to AWS S3 with automatic resizing including REST API.
Elixir
88
star
59

mvp

πŸ“² simplest version of the @dwyl app
Elixir
87
star
60

contributing

πŸ“‹ Guidelines & Workflow for people contributing to our project(s) on GitHub. Please ⭐ to confirm you've read & understood! βœ…
86
star
61

learn-flutter

πŸ¦‹ Learn how to use Flutter to Build Cross-platform Native Mobile Apps
JavaScript
86
star
62

javascript-best-practice

A collection of JavaScript Best Practices
83
star
63

learn-amazon-web-services

⭐ Amazing Guide to using Amazon Web Services (AWS)! ☁️
83
star
64

range-touch

πŸ“± Use HTML5 range input on touch devices (iPhone, iPad & Android) without bloatware!
JavaScript
83
star
65

learn-pre-commit

βœ… Pre-commit hooks let you run checks before allowing a commit (e.g. JSLint or check Test Coverage).
JavaScript
80
star
66

product-owner-guide

πŸš€ A rough guide for people working with dwyl as Product Owners
78
star
67

phoenix-ecto-append-only-log-example

πŸ“ A step-by-step example/tutorial showing how to build a Phoenix (Elixir) App where all data is immutable (append only). Precursor to Blockchain, IPFS or Solid!
Elixir
78
star
68

fields

🌻 fields is a collection of useful field definitions (Custom Ecto Types) that helps you easily define an Ecto Schema with validation, encryption and hashing functions so that you can ship your Elixir/Phoenix App much faster!
Elixir
77
star
69

goodparts

πŸ™ˆ An ESLint Style that only allows JavaScript the Good Parts (and "Better Parts") in your code.
JavaScript
77
star
70

hapi-error

β˜” Intercept errors in your Hapi Web App/API and send a *useful* message to the client OR redirect to the desired endpoint.
JavaScript
76
star
71

process-handbook

πŸ“— Contains our processes, questions and journey to creating a team
HTML
76
star
72

terminate

♻️ Terminate a Node.js Process (and all Child Processes) based on the Process ID
JavaScript
76
star
73

aws-lambda-deploy

☁️ πŸš€ Effortlessly deploy Amazon Web Services Lambda function(s) with a single command. Less to configure. Latest AWS SDK and Node.js v20!
JavaScript
74
star
74

dev-setup

✈️ A quick-start guide for new engineers on how to set up their Dev environment
73
star
75

hapi-login-example-postgres

🐰 A simple registration + login form example using hapi-register, hapi-login & hapi-auth-jwt2 with a PostgreSQL DB
JavaScript
69
star
76

flutter-bloc-tutorial

A step-by-step example/tutorial explaining the benefits of the BLoC architecture and bloc library including tests!
Dart
67
star
77

phoenix-liveview-todo-list-tutorial

βœ… Beginners tutorial building a Realtime Todo List in Phoenix 1.6.10 + LiveView 0.17.10 ⚑️ Feedback very welcome!
Elixir
65
star
78

learn-security

πŸ” For most technology projects Security is an "after thought", it does not have to be that way; let's be proactive!
64
star
79

learn-javascript

A Series of Simple Steps in JavaScript :-)
HTML
63
star
80

chat

πŸ’¬ Probably the fastest, most reliable/scalable chat system on the internet.
Elixir
62
star
81

learn-jsdoc

πŸ“˜ Use JSDoc and a few carefully crafted comments to document your JavaScript code!
CSS
60
star
82

ampl

πŸ“± ⚑ Ampl transforms Markdown into AMP-compliant html so it loads super-fast!
JavaScript
58
star
83

aguid

❄️ A Globally Unique IDentifier (GUID) generator in JS. (deterministic or random - you chose!)
JavaScript
57
star
84

tudo

βœ… Want to see where you could help on an open dwyl issue?
Elixir
57
star
85

learn-apple-watch-development

πŸ“— Learn how to build Native Apple Watch (+iPhone) apps from scratch!
Swift
55
star
86

learn-qunit

βœ… A quick introduction to JavaScript unit testing with QUnit
JavaScript
51
star
87

learn-ngrok

☁️ Learn how to use ngrok to share access to a Web App/Site running on your "localhost" with the world!
HTML
50
star
88

learn-jshint

πŸ’© Learn how to use the ~~jshint~~ code quality/consistency tool.
JavaScript
49
star
89

hapi-auth-jwt2-example

πŸ”’ A functional example Hapi.js app using hapi-auth-jwt2 & Redis (hosted on Heroku) with tests!
JavaScript
49
star
90

tachyons-bootstrap

πŸ‘’Bootstrap recreated using tachyons functional css
HTML
48
star
91

learn-tailwind

🌬️ Learn Tailwind CSS to craft pixel-perfect web apps/sites in less time! 😍
Elixir
48
star
92

esta

πŸ” Simple + Fast ElasticSearch Node.js client. Beginner-friendly defaults & Heroku support βœ… πŸš€
JavaScript
48
star
93

learn-node-js-by-example

☁️ Practical node.js examples.
HTML
47
star
94

elixir-pre-commit

βœ… Pre-commit hooks for Elixir projects
Elixir
46
star
95

product-roadmap

🌐 Because why wouldn't you make your company's product roadmap Public on GitHub?
46
star
96

redis-connection

⚑ Single Redis Connection that can be used anywhere in your node.js app and closed once (e.g in tests)
JavaScript
45
star
97

learn-graphQL

❓Learn to use GraphQL - A query language that allows client applications to specify their data fetching requirements
JavaScript
45
star
98

aws-lambda-test-utils

Mock event and context objects without fluff.
JavaScript
44
star
99

hapi-login

πŸšͺ The Simplest Possible (Email + Password) Login for Hapi.js Apps βœ…
JavaScript
43
star
100

learn-riot

🐎 Riot.js lets you build apps that are simpler and load/run faster than any other JS framework/library.
HTML
43
star