Skip to content

Instantly share code, notes, and snippets.

@angryobject
Last active November 23, 2019 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angryobject/49d32778ea9e6b56d00de12386072f00 to your computer and use it in GitHub Desktop.
Save angryobject/49d32778ea9e6b56d00de12386072f00 to your computer and use it in GitHub Desktop.
Sourcing .env files

.evn files are used to hold project-related environment variables. This can be helpful if you want to decouple some configuration details from you application logic and/or hide some sensitive information (you don't normally check in this type of files into you repo). An example of a .evn file could be:

.env
API_KEY=secret
PG='{"user":"angryobject","host":"some.remove.server","database":"testing","password":"strongpa$$word","port":5432}'

And example usage as follows:

server.js
const config = {
    pg: process.env.PG ? JSON.parse(process.env.PG) : {
        user: 'postgres',
        host: '127.0.0.1',
        database: 'postgres',
        password: null,
        port: 5432,
    },

    apiKey: process.env.API_KEY,
};

Here we store api key and remote database connection details (in a JSON string representation) and later use it to build our config file inside the application. But to get this actually working we need to make our variables avaliable for the program.

Normally you can export variables you want to use and then run the program:

$ export API_KEY=secret
$ node server.js

We can do the same thing with the .env file if you add export keyword in front of the variables and source the file before running the program:

.env
export API_KEY=secret
$ source .env && node server.js

But this pollutes our global scope leaving the variables avaliable after the program exits:

$ echo $API_KEY
secret

To avoid this normally we can prepend the command with the variable:

$ API_KEY=secret node server.js

But how do we do this with the .env file? If we try to source it the same way it just would not work (given you open a new terminal window so the already exported variables from the previous examples are gone).

With the little help of internet we can google the following solution:

$ env $(cat .evn | xargs) node server.js

This does the job done, leaving no traces of our variables in the wild. Viola!

To make it more usable (and avoid the need to remember the command) i wrapped it into a utility called renv (short for Run with EVN) with the usage as follows:

$ envr node server.js # uses .env file
$ envr .custom.env node server.js # uses .custom.env file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment