Contents
Why use environment variables in APIs
Environment variables are a key part of API development for several important reasons:
Prevent hardcoding of sensitive data
Putting sensitive information like API keys, secret tokens, or database passwords directly into your code is a huge security risk. If your code is ever made public, accidentally shared, or compromised, these secrets become exposed. Environment variables let you store these sensitive values outside your code, which significantly lowers this risk.
Enable secure management without code changes
APIs often run in different environments (like development, testing, or the live production version), and each might need different settings. Environment variables allow you to switch between these environments smoothly. You can change credentials or API addresses without touching your code, leading to cleaner workflows and safer deployments.
Enhance operational flexibility
With environment variables, you can update settings (like refreshing an API key) without having to stop and restart your entire application. This is a big advantage in live systems: it means no downtime, you can change keys regularly for security, and manage your settings consistently.
Secure local development
When you’re developing an application on your own computer, using a .env file (often loaded by tools like dotenv) keeps your sensitive information hidden locally. You make sure these .env files are not included in your version control system (like Git), so sensitive data doesn’t accidentally get shared with other developers or public code repositories.
Support robust secret handling in production
In live production environments, environment variables can be made even more secure by using special secret management tools like AWS Secrets Manager or HashiCorp Vault. These tools add layers of security, including encryption, control over who can access the secrets, detailed audit logs, and automated rotation of keys, which is crucial for protecting critical information.
Reduce risk of exposure from common mistakes
Credentials are often exposed by common errors, such as accidentally committing sensitive files to a code repository, secret values showing up in logs, or environment variables being baked directly into container images. Using environment variables correctly, combined with secure management practices, greatly reduces the chances of these mistakes leading to security breaches.
Creating environment variables
You can set environment variables in different ways, depending on whether you need them temporarily or permanently, and what operating system or programming language you’re using.
On the command line (Temporary)
These variables are active only for the current command prompt or terminal session. Once you close it, they’re gone.
Unix/macOS/Linux (bash, zsh):
export API_KEY="your_secret_key" # Or set it directly before a command: API_KEY="your_secret_key" node ./app.js
Windows (CMD):
set API_KEY="your_secret_key"
Windows (PowerShell):
$Env:API_KEY = "your_secret_key"
Permanent system/user-level variables
To make environment variables last even after you close your terminal or restart your computer:
Unix/Linux/macOS
Add export KEY=value lines to your shell’s profile file. Common files include ~/.bashrc, ~/.zshrc, or ~/.profile (the ~ means your home directory). After adding, you’ll need to run source ~/.bashrc (or the relevant file) or open a new terminal for changes to take effect.
Windows
You can use the System Properties graphical interface:
- Right-click “This PC” or “My Computer” -> “Properties”.
- Click “Advanced system settings”.
- Click “Environment Variables…”
- Here, you can add or edit variables for your user account or for the entire system.
Alternatively, using PowerShell:
[Environment]::SetEnvironmentVariable("API_KEY", "your_secret_key", "User")
# For system-wide:
# [Environment]::SetEnvironmentVariable("API_KEY", "your_secret_key", "Machine")
Using .env files for local development
.env files are a popular and simple way to manage environment variables specifically for local development workflows. They keep sensitive data out of your main code.
Create a .env file: In the root folder of your project, create a file named .env.
API_KEY=your_secret_key DATABASE_URL=postgres://user:pass@host/db DEBUG=True
Important: Always add .env to your .gitignore file so it’s not accidentally uploaded to your code repository. It’s also good practice to provide a .env.example file with placeholder values.
– Load in your code:
– In Node.js (using dotenv library): First, install it: npm install dotenv Then, at the very top of your main application file:
require('dotenv').config();
console.log(process.env.API_KEY);
– In Python (using python-dotenv library): First, install it: pip install python-dotenv Then, in your Python script:
from dotenv import load_dotenv import os load_dotenv() # This loads variables from .env into os.environ api_key = os.getenv("API_KEY") print(api_key)
In FastAPI/Pydantic (using pydantic-settings): First, install it: pip install “pydantic-settings”
from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): database_url: str api_key: str # Example field model_config = SettingsConfigDict(env_file=".env", extra="ignore") settings = Settings() print(settings.database_url) print(settings.api_key)
Setting environment variables in code (Runtime)
You can also set environment variables directly within your application’s code. However, these changes are not permanent and only affect the current running process and any processes it starts. They disappear once your application stops.
Python:
import os os.environ['NEW_VAR'] = 'value' print(os.environ['NEW_VAR'])
Node.js:
process.env.NEW_VAR = 'value'; console.log(process.env.NEW_VAR);
Best practices in API context
Here’s a detailed look at the best ways to use environment variables securely in both your local development setup and your live (production) API environments.
Local development
– Use .env files with a loader: Store specific settings for your different development stages (like .env.development, .env.test) in separate .env files. Use libraries such as dotenv for Node.js or python-dotenv for Python to load these variables into your application.
– Never commit .env to version control: It’s absolutely crucial to always add .env to your .gitignore file. This prevents sensitive information from being accidentally uploaded to your code repository. Instead, provide a clean template like .env.example with placeholder values for your teammates.
– Structure multiple environment files: For clarity and organisation, use dedicated .env files for each stage of development (e.g., .env.development, .env.production). Also, keep a template file updated for everyone.
– Validate configuration on startup: When your application starts, immediately check if all critical environment variables are present, have the correct data types, and follow the right format. Use validation tools (like Zod, envalid, or Pydantic) to “fail fast” if any important variables are missing or incorrectly formatted.
Production environments
– Skip .env in production: Never use .env files for your live applications. Instead, rely on dedicated secrets managers (like AWS Secrets Manager, HashiCorp Vault, Azure Key Vault) or platform-specific encrypted environment variables (like Heroku config vars, GitHub Actions secrets).
– Adopt centralised secret management: Follow industry best practices (like OWASP guidance) to manage your secrets. This means standardising how secrets are created and used, granting access only to what’s absolutely necessary, keeping records of all access, and regularly changing secret keys automatically.
– Inject secrets at runtime only: Avoid embedding secrets directly into your container images or application logs. Use tools that provide secrets to your application dynamically (as it’s running) to significantly reduce their exposure.
– Practice least privilege and audit: Only give read access to services that absolutely need it. Make sure all access events to your secrets are logged and can be traced for security checks.
– Automate rotation and expiry: Use secrets that are temporary or time-limited, and enforce automatic key rotation. This greatly reduces risk if a secret is ever leaked.
Encryption, memory, and leakage risks
– Consider encrypted secret files: For very sensitive situations, you might use encrypted .env.vault files or load secrets directly into memory-backed volumes for runtime access.
– Avoid overly exposing secrets: Be extremely careful about sensitive information appearing in logs, debugging output, or during environment dumps, especially in containerised environments like Kubernetes.
– Be cautious with environment variables for critical systems: For systems that are extremely important, consider alternatives to standard environment variables, such as secret files with very strict permissions or methods that inject secrets directly into memory only when the application is running.
Common pitfalls & mitigations
“Oops, I pushed .env!”:
Fix: Immediately remove the file from your Git history using git rm –cached .env and rotate (change) any exposed keys immediately.
Variable misnamed or missing in deployment?
Fix: Always create an .env.example file (a template for what variables are needed). Run validation scripts early in your CI/CD (Continuous Integration/Continuous Delivery) pipeline to catch these errors before deployment.
Secrets accidentally leaked in logs or debug output?
Fix: Implement log scrubbing (to remove sensitive data from logs), restrict debugging privileges, and immediately rotate any exposed secrets.
Sportmonks integration — Environment variables in action
Sportmonks’ APIs need an API token to prove who you are. This token should never be written directly into your code. Our docs show two ways to use your token:
– Include the token as a query parameter (?api_token=YOUR_TOKEN)
– Pass it via a request header (Authorization: Bearer YOUR_TOKEN)
Why environment variables are important here
Using environment variables for your Sportmonks token is crucial for several reasons:
– Security: By storing your token as an environment variable (for example, named SPORTMONKS_API_TOKEN), you make sure these sensitive details are kept out of your code files and aren’t accidentally put into version control (like Git), where others might see them.
– Flexibility: You can easily switch between different tokens for your development, testing, and live (production) environments simply by changing the environment variable’s value.
– Best practice: Whether you use .env files for local development or specialised secret management tools in production (like AWS Secrets Manager), using environment variables helps reduce security risks and follows secure deployment guidelines.
require('dotenv').config();
const axios = require('axios');
const token = process.env.SPORTMONKS_API_TOKEN;
axios.get('https://api.sportmonks.com/v3/football/fixtures', {
headers: { Authorization: `Bearer ${token}` }
});
This ensures your Sportmonks token stays outside your codebase, and you can swap environments simply by updating SPORTMONKS_API_TOKEN.
Keep your tokens safe, use environment variables
Your API token is the key to Sportmonks’ powerful football data, so don’t leave it exposed in your code. By using environment variables, either from .env files during development or secret managers in production, you protect sensitive credentials while keeping your app flexible across environments.
Switch tokens, update configurations, and deploy with confidence, all without touching a line of your code. Add SPORTMONKS_API_TOKEN to your environment setup and integrate the smart way today.




