Skip to main content
The init context (also called “init code”) is code in the global context that runs before the test starts. It has access to special functions and variables not available during main script execution.

Overview

Before k6 starts the test logic, code in the init context prepares the script by:
  • Importing modules
  • Loading files
  • Defining global variables
  • Setting up configuration
  • Initializing shared resources
Only a few special functions are available exclusively in the init context.
For details about the runtime and execution phases, refer to the Test Lifecycle documentation.

Init Context Functions

open()

function
Opens a file and reads all its contents into memory for use in the script.Parameters:
string
required
Path to the file (absolute or relative). The file is loaded once even when running with multiple VUs.
string
File read mode:
  • Omit or "t" - Read as text (default)
  • "b" - Read as binary data (ArrayBuffer)
Returns:
string | ArrayBuffer
File contents as string or ArrayBuffer (if binary mode)
open() can only be called from the init context. This restriction allows k6 to determine which local files to bundle when distributing tests across multiple nodes.

Global Variables

These variables are available throughout your script:

Environment Variables

object
Object containing environment variables as key-value pairs. Access environment variables passed to k6 via -e or --env flags.Example:

VU Information

number
Current VU (Virtual User) number. Starts at 1 and increments for each VU.Example:
number
Current iteration number for the VU. Starts at 0 and increments with each iteration.Example:
For more comprehensive execution context information, use the k6/execution module which provides detailed metadata about scenarios, instances, and test state.

Examples

Loading JSON Data

Loading Binary Files

Using Environment Variables

Run with environment variables:

Per-VU Data Assignment

Conditional Configuration

Run with:

Memory Efficiency with SharedArray

open() often consumes a large amount of memory because every VU keeps a separate copy of the file in memory.
To reduce memory consumption:

Use SharedArray

Use k6/experimental/fs

Init Context vs Default Function

Code Example

Best Practices

Keep init context code minimal and fast. Heavy operations in init context delay test startup and increase memory usage per VU.
Always use SharedArray when loading large files to avoid memory duplication across VUs.
Provide defaults for environment variables and validate required ones in init context.
Use __VU for per-VU data distribution and __ITER for iteration-specific logic.

k6/execution

Detailed execution context and metadata

SharedArray

Share data efficiently between VUs

k6/experimental/fs

Memory-efficient file operations

Test Lifecycle

Understanding k6 execution phases