.env & config files

Projected Time

About 20-30 minutes

Prerequisites

Here are links to lessons that should be completed before this lesson:

Motivation

Using a .env (pronounced “env”, “dot-env”, or “dot-E-N-V”) can help you avoid exposed authorization or login credentials by securing these as secret variables. If you add the .env containing your variables to your .gitignore right away, it will never get added or commited to GitHub, and your secrets stay local.

Objectives

Participants will be able to:

Specific Things to Learn

Materials

Lesson

.env files are for project environment variables.

These files often include sensitive data like:

But if it’s never on github, how do I share .env variables?

What is a config file?

Common Mistakes / Misconceptions

I’ll just remember to remove my sensitive data before every a commit.

Guided Practice

Let’s Try It

  1. Open a working node/express.js project
  2. Open your command line and navigate to the project you chose above

  3. Create an environment variable in your terminal

    export I_LOVE=lamp
    echo $I_LOVE

    You should get your value back:

    echo $I_LOVE
    lamp

    Enter env to see the list of your saved environment variables. You should see I_LOVE has been added.

  4. Close your terminal, open it, and try echoing it again in that same directory.

    echo $I_LOVE

    It’s gone! Your terminal session ended. Check your list again:

    env
  5. create a .env and a .env.sample in your project root

export I_LOVE=lamp
- In your .env.sample, add this line:

```
export I_LOVE=sample
```
  1. Add .env to your .gitignore right away!

  2. create a config.js if you don’t already have one.

exports.I_LOVE = process.env.I_LOVE;
  1. require your config variable in a server-side file. Put it in your server.js or app.js like this:
const I_LOVE = require('./config');
Then print your variable by adding this line to the file:
console.log("I love ", I_LOVE);
  1. Run your project and see if your line prints in the terminal.
  1. Type in the terminall, source .env, and then press enter. Now run your project. “lamp” should print in the console!

  2. Destructuring: object assignment
const { I_LOVE } = require('./config');
- Declaring I_LOVE gives that variable name to everything that config.js exported. Destructuring assignment unpacks the config object, picking out specific variables. Essentially, adding brackets is the same as saying:
```
const I_LOVE = require('./config').I_LOVE;
```
  1. In your terminal, press ctrl + c to stop your process. Start it again. You should see the variable you extracted!:
I love lamp
Your app is running on PORT 3000

Independent Practice

Check for Understanding