{"record":{"id":"22ac81ce6108c069","repo":"grafana/k6","slug":"new-sharedarray-must-be-called-in-the-init-context","errorCode":null,"errorMessage":"new SharedArray must be called in the init context","messagePattern":"new SharedArray must be called in the init context","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"internal/js/modules/k6/data/data.go","lineNumber":78,"sourceCode":"\n// Exports returns the exports of the data module.\nfunc (d *Data) Exports() modules.Exports {\n\treturn modules.Exports{\n\t\tNamed: map[string]any{\n\t\t\t\"SharedArray\": d.sharedArray,\n\t\t},\n\t}\n}\n\nconst asyncFunctionNotSupportedMsg = \"SharedArray constructor does not support async functions as second argument\"\n\n// sharedArray is a constructor returning a shareable read-only array\n// indentified by the name and having their contents be whatever the call returns\nfunc (d *Data) sharedArray(call sobek.ConstructorCall) *sobek.Object {\n\trt := d.vu.Runtime()\n\n\tif d.vu.State() != nil {\n\t\tcommon.Throw(rt, errors.New(\"new SharedArray must be called in the init context\"))\n\t}\n\n\tname := call.Argument(0).String()\n\tif name == \"\" {\n\t\tcommon.Throw(rt, errors.New(\"empty name provided to SharedArray's constructor\"))\n\t}\n\tval := call.Argument(1)\n\n\tif common.IsAsyncFunction(rt, val) {\n\t\tcommon.Throw(rt, errors.New(asyncFunctionNotSupportedMsg))\n\t}\n\n\tfn, ok := sobek.AssertFunction(val)\n\tif !ok {\n\t\tcommon.Throw(rt, errors.New(\"a function is expected as the second argument of SharedArray's constructor\"))\n\t}\n\n\tbuilder := func() (sharedArray, error) { return getSharedArrayFromCall(rt, fn) }","sourceCodeStart":60,"sourceCodeEnd":96,"githubUrl":"https://github.com/grafana/k6/blob/01ffac6f245854c1b8adc6a69857c76a15f90022/internal/js/modules/k6/data/data.go#L60-L96","documentation":"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.","triggerScenarios":"'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.","commonSituations":"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.","solutions":["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.","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.","For per-scenario data, create separate top-level SharedArrays with distinct names and pick the right one inside the VU code."],"exampleFix":"// before\nexport default function () {\n  const users = new SharedArray('users', () => data); // throws\n}\n\n// after\nconst users = new SharedArray('users', () => data);\nexport default function () {\n  // use users[...] here\n}","handlingStrategy":"validation","validationCode":"// SharedArray may only be constructed at module top level.\n// Static check: the 'new SharedArray' text must not appear inside exported functions.\n// k6 >= 0.5x also ships an ESLint-style rule in some templates; simplest guard:\nconst isInitContext = typeof __ENV !== 'undefined'; // not reliable - rely on placement instead","typeGuard":null,"tryCatchPattern":"try {\n  arr = new SharedArray(name, builder);\n} catch (e) {\n  if (/must be called in the init context/.test(e.message)) {\n    throw new Error('Move the new SharedArray(...) call to the top level of the script');\n  }\n  throw e;\n}","preventionTips":["Keep all new SharedArray(...) calls in the first screenful of the script, above export default.","Code-review rule: constructors of k6 data APIs never appear inside exported functions.","When extracting helpers, pass the built SharedArray in - never construct it inside runtime helpers."],"tags":["k6","sharedarray","init-context","data"],"backgroundTag":"k6-init-context-violation","analyzedSha":"01ffac6f245854c1b8adc6a69857c76a15f90022","analyzedAt":"2026-08-18T03:05:52.393Z","contentChangedAt":"2026-08-18T03:05:52.393Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}