Skip to Content
Course content

148: Environment Variables in Node

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're renting out a vacation home on Airbnb. You create a "Welcome Guide" for your guests that tells them how to use the coffee machine, where the extra towels are, and how to lock the front door. Now, imagine you have two different properties—one in the mountains and one at the beach. You don't want to write two completely different guidebooks; that's a maintenance nightmare. Instead, you leave a few blank spaces in the guide, like "The WiFi password is: ___________."

When you leave the guide at the mountain house, you scribble in the mountain WiFi password. When you leave it at the beach house, you scribble in the beach password. The guide (your code) stays exactly the same, but the specific details (your environment variables) change depending on where the guide is physically located.

In Node.js, this is exactly how we handle things like database passwords, API keys, or port numbers. You don't want to hardcode your production database password into your script, because then anyone with access to your GitHub repo has the keys to your kingdom. Instead, you tell Node: "Look at the environment you're running in and find the value for this specific key."

Tapping into process.env

Node provides a global object called process, and inside that is an object called env. This is where Node stores all the environment variables available to the current process. I've seen plenty of developers try to create their own "config.js" file, but process.env is the industry standard because it keeps secrets out of your version control.

Here is how you actually access a variable in your code:

const dbPassword = process.env.DB_PASSWORD;
const port = process.env.PORT || 3000; // A common trick: use the env var, or default to 3000

Notice that second line. I almost always provide a fallback value for things like ports. If you're running the app locally and forgot to set the variable, the app won't just crash—it'll just use 3000.

The .env Workflow and the Danger Zone

Typing variables into your terminal every time you start the app is tedious. That's why we use a package called dotenv. It allows you to create a file named .env in your project root where you can list your variables in a simple KEY=VALUE format.

Your .env file would look like this:

STRIPE_API_KEY=sk_test_4eC39HqLyjWDarjtT1zdp7dc
DB_CONNECTION_STRING=mongodb+srv://user:pass@cluster.mongodb.net/myApp

To make Node recognize these, you just add require('dotenv').config() at the very top of your entry file. From that point on, process.env.STRIPE_API_KEY will magically contain that string.

Now, here is the part where I need you to pay close attention: You must add .env to your .gitignore file. If you commit your .env file to GitHub, you have just leaked your secrets to the world. I've seen professional engineers get fired for this, and I've seen companies lose thousands of dollars to bots that scrape GitHub for AWS keys. Never, ever commit your actual environment files.

Handling Different Stages

You'll typically encounter three environments: development, staging, and production. In development, your DB_CONNECTION_STRING might point to localhost:27017. In production, it will point to a secure, managed cluster in the cloud.

The beauty of this setup is that you don't change a single line of JavaScript when you deploy. You simply change the environment variables on your hosting platform (like Heroku, Vercel, or AWS), and your code adapts automatically.




📋 Practical Task

Exercise: Securing a Stripe API Key for a Payment Simulator

You are building a payment processing simulation. You have a sensitive API key that must not be hardcoded into the source code.

  • Create a file named .env and add a variable called STRIPE_SECRET_KEY with a fake value (e.g., sk_test_12345).
  • Create a file named app.js.
  • Install and initialize dotenv at the top of app.js.
  • Write a function called processPayment(amount) that logs a message to the console: "Processing payment of $[amount] using key: [your secret key]".
  • The function must retrieve the key using process.env.
  • Add a check: if STRIPE_SECRET_KEY is missing from the environment, the function should log "Error: API Key not configured!" instead of attempting the payment.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.