grafana/k6 · error

the "%s" function is only available in the init stage (i.e.

Error message

the "%s" 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

Init-context guard in requireImpl.require: 'require' was called outside the init stage. k6 only allows module loading in the global/init context (__VU==0 or setup); calling require inside a VU iteration function (default function body) is rejected.

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 01ffac6f24)

Solutions

  1. Move the require() call to the top level of the script (init context)
  2. Use static import/require at module scope: const lib = require('k6/http')
  3. See https://grafana.com/docs/k6/latest/using-k6/test-lifecycle/ for the test lifecycle
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at internal/js/bundle.go:456 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of grafana/k6@01ffac6f24 (2026-08-18). Data as JSON: /api/errors/247fd01db0ca2028. Report an issue: GitHub.