Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active February 6, 2024 20:57
Show Gist options
  • Star 88 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save ericelliott/4152984 to your computer and use it in GitHub Desktop.
Save ericelliott/4152984 to your computer and use it in GitHub Desktop.
env-examples

Most configuration really isn't about the app -- it's about where the app runs, what keys it needs to communicate with third party API's, the db password and username, etc... They're just deployment details -- and there are lots of tools to help manage environment variables -- not the least handy being a simple .env file with all your settings. Simply source the appropriate env before you launch the app in the given env (you could make it part of a launch script, for instance).

env files look like this:

SOMEVAR="somevalue"
ANOTHERVAR="anothervalue"

To source it:

$ source dev.env  # or staging.env, or production.env, depending on where you're deploying to

Don't check these files into the repo... instead, check in something like dev.example.env, containing some sensible defaults, minus your app secrets, of course. Devs wishing to collaborate should copy the file to the real filename, set the values appropriately, and they're off to the races.

It's easy to add scripts via npm, so you can source the appropriate env file by running commands:

In your package.json:

scripts: {
  "start-dev": "source dev.env; node server.js"
  "start-prod": "source prod.env; node server.js"
}

Then start it up:

$ npm run start-prod
@alielzei
Copy link

alielzei commented Apr 2, 2017

you my friend are a simple genius

@robophil
Copy link

@Alizzen, my thoughts exactly

@JohnnyBizzel
Copy link

I get "source" not found. What is "source"?

@PiP-iT-Global
Copy link

To use a custom script you need the 'run' flag:

npm run start-prod

@thibauds
Copy link

thibauds commented May 6, 2019

If you get sh: 1: source: not found this is because your shell does not support source, try using .:
replace source dev.env by . dev.env

@katekostina
Copy link

I want to add that if you use webpack, you might want tot install dotenv package. I've found this advice here.

@andythedishwasher
Copy link

Beautiful solution to a problem that's been vexing me for quite awhile in my full stack adventures. Thanks a million.

@lacherogwu
Copy link

is it a replacement for something like dotenv?

@Leo3965
Copy link

Leo3965 commented Jan 31, 2024

Nice explanation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment