Skip to content

k6 Environment Variables Not Accessible Fix

DodaTech Updated 2026-06-24 3 min read

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_NAME instead of process.env.VAR_NAME
  • Always provide default values with ||
  • Pass variables via -e flag 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

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [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

### Can I set environment variables in the k6 script itself?

No, __ENV is read-only inside the script. Environment variables must be set externally via the -e CLI flag or shell environment variables. You can use computed variables (e.g., const myVar = __ENV.VAR || 'default') but not set them.

How do I use secrets in k6?

Pass secrets via environment variables with -e SECRET=value. Do not hardcode secrets in scripts. For CI/CD, use your pipeline's secret manager to inject values into the -e flags. k6 Cloud also supports secret environment variables.

Why is __ENV empty inside the default function?

__ENV is populated at module load time from shell environment variables plus -e flags. If using Docker, ensure you pass -e flags to the k6 run command inside the container, not just to docker run.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro