This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Manage Configuration Values with Environment Variables

    Mark ShustMark Shust

    Storing configuration in files instead of the environment has many downsides, including mistakenly checking in the wrong configuration in the wrong environment, coupling configuration with code, and scaling issues in larger server architectures.

    We’ll learn how to update app code to look at environment variables for configuration values instead of using configuration files, and different approaches for managing environment variables between dev/stage/prod.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 Let's create a new project named Foo. In there, let's create a simple Node.js script that connects to a locally running MongoDB instance. We'll install the MongoDB module with Yarn, and then start our script with Node. We can see that we can successfully connect to our MongoDB instance.

    00:22 The current configuration doesn't allow for the connection string to be changed on the fly. Moving configuration values into environment variables has many benefits. Let's go ahead and copy the connection string, and replace it with a reference to our environment variable.

    00:38 Environment variables are referenced by process.env, followed by the name of our environment variable in caps. In this case, we'll name it Mongo_URI. Let's save our file. We'll start the Node script again, but this time prepend the command with our new environment variable.

    00:59 We can see that we can still connect to the database, but our connection string is moved out of code and into the environment. If you have many environment variables or want an easier way to start your script, you can create a new .env file and move your environment variables there.

    01:17 To inject our external environment file into our Node.js script, we'll need a package called .env. Let's add it with Yarn. Next, we'll require this module at the top of our script, immediately invoking the config function. This function will automatically look for a file named .env, and inject the values contained within this file into the environment.

    01:43 Let's go back and start our Node process directly now, and see that we are still connecting to the MongoDB instance from the values within our environment file.

    Discuss

    Discuss