Environment Variables
Environment variables keep secrets out of your code, and have different settings for different stages of your application (like development, testing, and production).
What are Environment Variables
Environment variables are key-value pairs stored outside of your application's configuration that can affect how it runs.
They're often used for:
Configuring different environments (development, production, etc.).
Storing secrets, like API keys, which should not be hard-coded or stored in the source code.
Parameterizing settings so that they can be changed without altering the application's code.
Setting Environment Variables
On Your Local Development Machine
Windows (Command Prompt):
Windows (PowerShell):
Linux/macOS:
Reading Environment Variables in Code
Python:
Node.js:
Using .env
Files for Local Development
.env
Files for Local DevelopmentFor local development, instead of setting variables in the command line every time, you can use .env
files.
Tools like dotenv
for Node.js and python-decouple
for Python allow you to load environment variables from .env
files into your application.
Example .env file:
Environment Variables in Production
In production, environment variables can be set:
Directly on the server: Use the methods mentioned above.
Using a platform's dashboard: Platforms like Heroku or AWS Elastic Beanstalk allow you to set environment variables via their dashboard.
Container Orchestration Systems: Systems like Kubernetes allow you to set environment variables for your containers in your deployment configurations.
Best Practices
Don't Commit Secrets: Never commit secrets (API keys, database passwords, etc.) to version control. Instead, use environment variables.
Use
.env
files for Local Development Only:.env
files are great for local development but shouldn't be used in production settings. Instead, set environment variables directly on your production servers or through your orchestration tool.Have Clear Documentation: If you're working on a team, ensure everyone knows what environment variables are required for the application to run and what they're used for.
Some environment variables can be set as key-value in softwares such as gitlab & when you push code it automatically identifies these variables
Last updated