grafana/k6 · error

new SharedArray must be called in the init context

Error message

new SharedArray must be called in the init context

What it means

SharedArray is k6's mechanism for sharing one copy of read-only data across all VUs; it must be built once during the init phase so every VU gets the same, deduplicated memory. The constructor checks d.vu.State() and throws this error when that value is non-nil, i.e. when the constructor runs in a VU/setup/teardown execution context instead of the init context.

Solutions

  1. Move the 'new SharedArray(...)' call to the top level of the script (init context), outside every exported function, and reference the variable inside default/setup.
  2. If the array is built at runtime per-VU on purpose, use a plain JavaScript array - it just won't be shared or deduplicated across VUs.
  3. For per-scenario data, create separate top-level SharedArrays with distinct names and pick the right one inside the VU code.

Example fix

// before
export default function () {
  const users = new SharedArray('users', () => data); // throws
}

// after
const users = new SharedArray('users', () => data);
export default function () {
  // use users[...] here
}
Defensive patterns

Strategy: validation

Validate before calling

// SharedArray may only be constructed at module top level.
// Static check: the 'new SharedArray' text must not appear inside exported functions.
// k6 >= 0.5x also ships an ESLint-style rule in some templates; simplest guard:
const isInitContext = typeof __ENV !== 'undefined'; // not reliable - rely on placement instead

Try / catch

try {
  arr = new SharedArray(name, builder);
} catch (e) {
  if (/must be called in the init context/.test(e.message)) {
    throw new Error('Move the new SharedArray(...) call to the top level of the script');
  }
  throw e;
}

Prevention

When it happens

Trigger: 'new SharedArray(name, fn)' executed inside export default function(), setup(), teardown(), or any function called from them - anywhere a VU state exists. Also when a helper module invoked at runtime calls the constructor.

Common situations: Refactoring a script and moving data setup into the default function to 'load it lazily'; wrapping SharedArray creation in a getArray() utility that gets called during the test; copy-pasting example code that constructs the array inside a loop.

Related errors


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

Appendix: source

Thrown at internal/js/modules/k6/data/data.go:78

// Exports returns the exports of the data module.
func (d *Data) Exports() modules.Exports {
	return modules.Exports{
		Named: map[string]any{
			"SharedArray": d.sharedArray,
		},
	}
}

const asyncFunctionNotSupportedMsg = "SharedArray constructor does not support async functions as second argument"

// sharedArray is a constructor returning a shareable read-only array
// indentified by the name and having their contents be whatever the call returns
func (d *Data) sharedArray(call sobek.ConstructorCall) *sobek.Object {
	rt := d.vu.Runtime()

	if d.vu.State() != nil {
		common.Throw(rt, errors.New("new SharedArray must be called in the init context"))
	}

	name := call.Argument(0).String()
	if name == "" {
		common.Throw(rt, errors.New("empty name provided to SharedArray's constructor"))
	}
	val := call.Argument(1)

	if common.IsAsyncFunction(rt, val) {
		common.Throw(rt, errors.New(asyncFunctionNotSupportedMsg))
	}

	fn, ok := sobek.AssertFunction(val)
	if !ok {
		common.Throw(rt, errors.New("a function is expected as the second argument of SharedArray's constructor"))
	}

	builder := func() (sharedArray, error) { return getSharedArrayFromCall(rt, fn) }

View on GitHub (pinned to 01ffac6f24)