The Complete, Easy Guide to Heroku Environment Variables
Imagine you are building a beautiful house. You have the blueprint, the bricks, and the wood. But for the house to actually work, it needs utilities: electricity, water, and gas. These utilities are vital, but you don’t build them into the walls. Instead, you connect the house to external supplies that provide these things.
Developing a software application is very similar. You write the code (the walls), but the application needs certain “utilities” to run. It needs to know which database to talk to, which secret key to use to lock up user data, or which port number to listen to on the internet.
When you use a platform like Heroku to host your application, you don’t want to write these “utilities”—like passwords or database addresses—directly into your code. Why? Because anyone who looks at your code (like on GitHub) could see your passwords. It’s like pasting your bank PIN on your front window.
The solution to this problem is using Heroku environment variables.
This guide will explain exactly what Heroku environment variables are, why they are crucial for your security, and how to use them easily, step-by-step.
Heroku Environment Variables
What are Environment Variables?
Before we dive into the Heroku-specific part, let’s understand the basic concept. An “environment variable” is just a simple setting with a name (a key) and a value. You can think of it like a sticky note attached to your application.
When your application starts up, it looks at its sticky notes to know how it should behave.
Examples of sticky note settings might be:
COLOR=blueMAX_USERS=100DATABASE_ADDRESS=secret_server
These are settings outside of the actual Python, Node.js, or Ruby code. They belong to the computer environment where the app is running.
When you develop an app on your personal laptop (your “local environment”), you might set these variables directly on your computer. When you move the app to Heroku (the “production environment”), you need a way to set these variables on Heroku’s computers. This is where Heroku environment variables come in.
Note: On Heroku, these are sometimes referred to as “Config Vars,” but they are essentially the same thing as environment variables.
Heroku Environment Variables
Why Must You Use Heroku Environment Variables?
If you are new to programming, it’s tempting to just write DATABASE_PASSWORD = "my_super_secret_password" directly into your code. However, you should never, ever do this for professional apps. Here are the three massive reasons why you must use Heroku environment variables instead.
1. Security (Keeping Secrets Secret)
This is the most critical reason. Modern software development involves sharing code. You likely use a system like Git and a service like GitHub or GitLab. When you “push” your code to GitHub, anyone with access to that repository can see everything.
If you hard-code passwords, API keys for services like Stripe or Mailgun, or database credentials, you have just leaked them. Bad actors have automated bots that scan GitHub looking for these secrets. If they find them, they can steal your data, run up huge bills on your cloud accounts, or destroy your database.
By using Heroku environment variables, these secrets live safely inside Heroku’s secure dashboard. They never enter your Git code repository. Your code just says: “Look up the password called DB_PASSWORD in the Heroku environment.”
2. Flexibility Across Environments
Your application will live in different places during its life.
Local Development: On your laptop.
Staging: A test version on Heroku.
Production: The real version on Heroku that real customers use.
Your application needs different settings for these different places. On your laptop, you might connect to a local database with no password. On Staging, you connect to a test database. On Production, you connect to the main, powerful database.
You cannot change your code every time you move it. That would be chaotic. Instead, you write the code to look for a variable named DATABASE_URL.
On your laptop, you set the variable
DATABASE_URLtolocal_db.On Heroku, you set the variable
DATABASE_URLto the real connection string.
The code remains the same, but it behaves differently because of the different Heroku environment variables set in each location.
3. Handling Change easily
What happens if your external database provider changes their password policy and you need to update your application’s database password?
If the password is hard-coded, you must open your code, change it, save it, commit the change to Git, and re-deploy your entire app to Heroku. That is a 10-minute job just to change a simple password.
If you use Heroku environment variables, you simply open the Heroku dashboard, edit the variable’s value, and save it. Heroku automatically restarts your application with the new value. It takes 10 seconds.
Heroku Environment Variables
How to Set Heroku Environment Variables
Heroku makes managing these variables very easy. There are two primary ways to do it: using the Heroku Dashboard (Web UI) and using the Heroku Command Line Interface (CLI).
We will walk through both.
Method 1: Using the Heroku Dashboard (Easiest for Beginners)
If you don’t like using a terminal or command prompt, this is the best method for you.
Log in: Go to heroku.com and log into your account.
Select Your App: You will see a list of your applications. Click on the name of the app you want to configure.
Go to Settings: At the top of the application dashboard, you will see tabs like Overview, Resources, Deploy, Metrics. Click on the Settings tab.
Find Config Vars: Scroll down on the Settings page until you see a section titled Config Vars. It has a subtitle: “Config vars are environment variables that can contain app configuration.”
Click “Reveal Config Vars”: This button unlocks the section so you can see existing variables and add new ones.
Add Your Variable: You will see two input boxes: KEY and VALUE.
KEY: The name you will use in your code to refer to the setting (e.g.,
GREETING_MESSAGE).VALUE: The actual secret data or setting (e.g.,
Hello from Heroku!).
Click Add: Once you click “Add,” that Heroku environment variable is saved. Heroku will immediately restart your application so it can detect this new variable.
Method 2: Using the Heroku CLI (Faster for Power Users)
If you are comfortable using the terminal (Mac/Linux) or Command Prompt/PowerShell (Windows), the CLI is much faster. Assuming you have already installed the Heroku CLI and logged in (heroku login):
Open your terminal in your app’s directory.
Set a variable: Use the
config:setcommand followed byKEY=VALUE.Bashheroku config:set GREETING_MESSAGE="Hello from the Terminal"Check your variables: To see all the Heroku environment variables set for your app, just type:
Bashheroku configView a specific variable: If you just want to see the value of one variable:
Bashheroku config:get GREETING_MESSAGERemove a variable: If you need to delete a setting, use the
config:unsetcommand:Bashheroku config:unset GREETING_MESSAGE
Every time you run config:set or config:unset, Heroku restarts your application with the new configuration.
Heroku Environment Variables
How to Use Environment Variables in Your Code
Now that you know how to set Heroku environment variables, you need to know how to read them from your code. The syntax depends on your programming language, but it is always simple.
In Python
Python uses the built-in os library to access environment variables.
import os
# Get the value of the GREETING_MESSAGE variable
# If it doesn't exist, it will return None
greeting = os.environ.get('GREETING_MESSAGE')
if greeting:
print(greeting)
else:
print("Welcome!")
In Node.js (JavaScript)
Node.js provides the variables directly on the global process.env object.
// Get the value of the GREETING_MESSAGE variable
const greeting = process.env.GREETING_MESSAGE;
if (greeting) {
console.log(greeting);
} else {
console.log("Welcome!");
}
The Special PORT Environment Variable
When you run your app on your laptop, you might decide to run it on port 3000 or port 5000. On Heroku, however, you cannot choose your port. Heroku dynamic assigns a port to your app just before it starts up.
You must write your code to listen to the dynamic port Heroku provides. Thankfully, Heroku provides this port to your app as a specific Heroku environment variable simply named PORT.
Here is why this is important:
Your app must listen on the port provided by
process.env.PORT(oros.environ.get('PORT')).If you hard-code port 3000, your app will fail on Heroku.
Example in Node.js for PORT:
const express = require('express');
const app = express();
// Very important: Use Heroku's PORT, or default to 3000 if running locally
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Your dynamic port is working!');
});
app.listen(port, () => {
console.log(`Application is running on port: ${port}`);
});
Best Practices and Common Mistakes
To get the most out of Heroku environment variables, follow these industry best practices.
1. Naming Conventions: Uppercase and Underscores
By convention, environment variables are written in all uppercase letters, with underscores separating words.
Good:
DATABASE_PASSWORD,STRIPE_API_KEY,MAX_LOGINS.Bad:
database_password,StripeApiKey.
This convention makes it immediately obvious in your code that you are dealing with a setting outside the code itself.
2. Don’t share keys even in environment variables
While you are setting Heroku environment variables inside the Heroku dashboard, you still need a way to manage these settings locally on your laptop.
Many developers create a local file often named .env. This file contains KEY=VALUE pairs for local testing.
The Crucial Step: Add .env to your .gitignore file immediately. You do not want your local .env file containing your local passwords ending up on GitHub. Each team member should have their own local .env file tailored to their computer. When the app goes to Heroku, Heroku’s settings take over.
Heroku Environment Variables
3. Handle Missing Variables Gracefully
What happens if a developer forgets to set a necessary Heroku environment variable? Your application might start, try to connect to the database with a None or undefined password, and then crash. This makes it hard to debug.
A good practice is to “validate” that the essential variables exist right when the app starts.
Graceful Handling Example (Python):
import os
import sys
# Crucial variables must exist for the app to work
REQUIRED_VARS = ['DATABASE_URL', 'STRIPE_KEY']
# Check each one
for var in REQUIRED_VARS:
if not os.environ.get(var):
print(f"FATAL ERROR: The environment variable {var} is not set.")
print("Please set this variable and restart the application.")
sys.exit(1) # Shut down the app immediately with an error code
# If we get here, we can proceed safely
database_url = os.environ.get('DATABASE_URL')
Advanced Feature: Automated Variables from Heroku Add-ons
Heroku provides an “Add-ons” ecosystem. These are pre-configured services like databases (Heroku Postgres), logging services (Papertrail), or Redis caches.
The wonderful thing about Heroku Add-ons is that they automatically manage their own Heroku environment variables.
When you attach a Heroku Postgres database to your app, Heroku instantly creates a new environment variable named DATABASE_URL and populates it with the correct connection string.
You don’t need to copy/paste the database password yourself. This automation is powerful because if Heroku needs to rotate your database password for security reasons, it will automatically update the DATABASE_URL variable for you, and your app will seamlessly connect using the new password without you knowing anything changed. This highlights the magic of letting Heroku environment variables act as the connector between your code and external services.
Heroku Environment Variables
Conclusion
Understanding Heroku environment variables is a major step in transforming from a beginner developer into a professional one. They are not just an advanced “nice-to-have” feature; they are an essential tool for creating secure, flexible, and robust cloud applications.
By keeping your application settings and secrets in Heroku environment variables, you protect your data, ensure your code can run effortlessly on different computers (your laptop vs. Heroku’s servers), and make managing updates incredibly fast and simple.
The simple habit of never hard-coding secrets and always using Heroku environment variables instead is one of the single best security practices you can adopt today. Start using them in your next project, and you will build better, safer apps.

