{"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/93accf6570dcd306ca5e99cc44c393ee3797761b/internal/js/modules/k6/data/data.go#L60-L96","documentation":"SharedArray must be constructed in the init context so its contents are serialized once and shared read-only across all VUs. data.go:76-80 throws when d.vu.State() != nil — meaning the constructor ran in the VU stage (inside export default, setup, or teardown) where cross-VU sharing is impossible.","triggerScenarios":"Placing `new SharedArray(...)` inside export default function(), setup(), teardown(), or any function first invoked during the VU stage rather than at module top level.","commonSituations":"Refactors that move data loading into the default function; newcomers unfamiliar with k6's init-vs-VU stages; conditionally building arrays inside iteration code.","solutions":["Move the SharedArray constructor to the top level of the script (init context)","Keep only references to the array inside export default / setup / teardown","If data depends on init-time computation, do it with open() and JSON.parse at top level, then wrap in SharedArray"],"exampleFix":"// before\nexport default function () {\n  const users = new SharedArray('users', () => [/* ... */]); // throws\n  // ...\n}\n\n// after\nconst users = new SharedArray('users', () => [/* ... */]); // init context\nexport default function () {\n  const u = users[Math.floor(Math.random() * users.length)];\n}","handlingStrategy":"validation","validationCode":"// Structural check (static, not runtime): the constructor call must sit at module\n// top level, outside export default / setup / teardown.\n// Place data setup like this:\nconst data = JSON.parse(open('./data.json'));\nconst shared = new SharedArray('data', function () { return data; });","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Keep all SharedArray constructors at the top level of the entry script","Review refactors that move init code into default/setup functions","Reference the array inside export default — never construct it there"],"tags":["shared-array","init-context","k6"],"backgroundTag":null,"analyzedSha":"93accf6570dcd306ca5e99cc44c393ee3797761b","analyzedAt":"2026-08-15T21:23:27.118Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}