k6 Environment Variables Not Accessible Fix
In this tutorial, you'll learn about k6 environment variables not accessible fix. We cover key concepts, practical examples, and best practices.
Your k6 script throws undefined when accessing __ENV.BASE_URL — environment variables passed with -e are not being read, or you are trying to use process.env which does not exist in k6's JavaScript runtime.
The Problem
import http from 'k6/http';
// WRONG: using Node.js process.env
const baseUrl = process.env.BASE_URL || 'http://localhost:8080';
export default function () {
http.get(baseUrl + '/health');
}
ERRO[0000] ReferenceError: process is not defined
k6's JavaScript runtime (goja) does not support Node.js globals. Environment variables are accessed via __ENV.
Step-by-Step Fix
1. Use __ENV for environment variables
import http from 'k6/http';
const baseUrl = __ENV.BASE_URL || 'http://localhost:8080';
export default function () {
http.get(baseUrl + '/health');
}
2. Pass variables via CLI
# Single variable
k6 run -e BASE_URL=https://api.example.com script.js
# Multiple variables
k6 run \
-e BASE_URL=https://api.example.com \
-e API_KEY=abc123 \
-e ENVIRONMENT=staging \
script.js
3. Use .env files (via shell)
# Load from .env file
export $(cat .env | xargs) && k6 run script.js
4. Handle missing variables gracefully
import http from 'k6/http';
const config = {
baseUrl: __ENV.BASE_URL || 'http://localhost:8080',
apiKey: __ENV.API_KEY,
environment: __ENV.ENVIRONMENT || 'development',
vuCount: parseInt(__ENV.VU_COUNT) || 10,
};
export const options = {
vus: config.vuCount,
duration: '30s',
};
export default function () {
if (!config.apiKey) {
console.log('WARNING: API_KEY not set');
}
const res = http.get(config.baseUrl + '/health', {
headers: config.apiKey ? { 'X-API-Key': config.apiKey } : {},
});
console.log(`[${config.environment}] ${config.baseUrl} → ${res.status}`);
}
5. Use tags from environment variables
import http from 'k6/http';
const tags = {
environment: __ENV.ENVIRONMENT || 'dev',
build: __ENV.BUILD_ID || 'local',
region: __ENV.REGION || 'us-east-1',
};
export const options = {
tags: tags,
thresholds: {
http_req_duration: ['p(95)<2000'],
},
};
export default function () {
http.get(__ENV.TARGET_URL || 'https://api.example.com');
}
Expected output:
environment=staging build=123 region=us-east-1
http_req_duration........: avg=145ms p(95)=320ms
✓ Tags applied from environment
Prevention Tips
- Use
__ENV.VAR_NAMEinstead ofprocess.env.VAR_NAME - Always provide default values with
|| - Pass variables via
-eflag on the command line - Use tags from env vars for test run identification
- Validate critical variables at module load time
Common Mistakes with env variables
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world K6 code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro