grafana/k6 · error

the "require" function is only available in the init stage (

Error message

the "require" function is only available in the init stage (i.e. the global scope), see https://grafana.com/docs/k6/latest/using-k6/test-lifecycle/ for more information

What it means

k6 scripts run in two stages: the init stage (top-level code, __VU==0) where modules load, and the VU stage (setup/default/teardown) where iterations execute. require() is bound only for the init context - the requireImpl guard in internal/js/bundle.go:456 checks it and throws when require is reached from VU-stage code. Module loading must happen once up front so every VU shares the same modules.

Source

Thrown at internal/js/bundle.go:456

				globalThis = newGlobal
			}),
			sobek.FLAG_TRUE, sobek.FLAG_TRUE)
		if err != nil {
			return err
		}
	}
	return nil
}

// this exists only to make the check in the init context.
type requireImpl struct {
	inInitContext func() bool
	modSys        *modules.ModuleSystem
}

func (r *requireImpl) require(specifier string) (*sobek.Object, error) {
	if !r.inInitContext() {
		return nil, fmt.Errorf(cantBeUsedOutsideInitContextMsg, "require")
	}
	return r.modSys.Require(specifier)
}

func (b *Bundle) setInitGlobals(rt *sobek.Runtime, vu *moduleVUImpl, modSys *modules.ModuleSystem) {
	mustSet := func(k string, v any) {
		if err := rt.Set(k, v); err != nil {
			panic(fmt.Errorf("failed to set '%s' global object: %w", k, err))
		}
	}

	impl := requireImpl{
		inInitContext: func() bool { return vu.state == nil },
		modSys:        modSys,
	}

	mustSet("require", impl.require)

View on GitHub (pinned to 93accf6570)

Solutions

  1. Move the require() call to the top level of the script (init stage)
  2. Or switch to ESM: `import http from 'k6/http';` at the top of the file
  3. For per-VU behavior, load the module once at init and branch on __VU inside the default function

Example fix

// before: require inside the default function
export default function () {
  const http = require('k6/http');
  http.get('https://k6.io');
}

// after: load in the init stage
const http = require('k6/http'); // or: import http from 'k6/http';
export default function () {
  http.get('https://k6.io');
}
Defensive patterns

Strategy: validation

Validate before calling

# heuristic static check: require() on an indented line is inside a function (VU stage)
grep -nP '^[[:space:]]+.*\brequire\(' script.js && \
  { echo 'require() found outside top-level init code'; exit 1; }

Prevention

When it happens

Trigger: Calling require('k6/http') (or any module) inside the exported default function, setup(), teardown(), handleSummary, or any helper they invoke; lazy/conditional require inside a function body.

Common situations: Refactors that move imports into functions 'for performance'; Node.js samples with lazy require() copied into iterations; attempting to load a different module per iteration or per VU.

Related errors


AI-assisted analysis of grafana/k6@93accf6570 (2026-08-15). Data as JSON: /api/errors/a36f80076b43a890. Report an issue: GitHub.