{"record":{"id":"247fd01db0ca2028","repo":"grafana/k6","slug":"the-s-function-is-only-available-in-the-init-st","errorCode":null,"errorMessage":"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","messagePattern":"the \"(.+?)\" 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","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"internal/js/bundle.go","lineNumber":456,"sourceCode":"\t\t\t\tglobalThis = newGlobal\n\t\t\t}),\n\t\t\tsobek.FLAG_TRUE, sobek.FLAG_TRUE)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// this exists only to make the check in the init context.\ntype requireImpl struct {\n\tinInitContext func() bool\n\tmodSys        *modules.ModuleSystem\n}\n\nfunc (r *requireImpl) require(specifier string) (*sobek.Object, error) {\n\tif !r.inInitContext() {\n\t\treturn nil, fmt.Errorf(cantBeUsedOutsideInitContextMsg, \"require\")\n\t}\n\treturn r.modSys.Require(specifier)\n}\n\nfunc (b *Bundle) setInitGlobals(rt *sobek.Runtime, vu *moduleVUImpl, modSys *modules.ModuleSystem) {\n\tmustSet := func(k string, v any) {\n\t\tif err := rt.Set(k, v); err != nil {\n\t\t\tpanic(fmt.Errorf(\"failed to set '%s' global object: %w\", k, err))\n\t\t}\n\t}\n\n\timpl := requireImpl{\n\t\tinInitContext: func() bool { return vu.state == nil },\n\t\tmodSys:        modSys,\n\t}\n\n\tmustSet(\"require\", impl.require)\n","sourceCodeStart":438,"sourceCodeEnd":474,"githubUrl":"https://github.com/grafana/k6/blob/01ffac6f245854c1b8adc6a69857c76a15f90022/internal/js/bundle.go#L438-L474","documentation":"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.","triggerScenarios":"Thrown at internal/js/bundle.go:456 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":["Move the require() call to the top level of the script (init context)","Use static import/require at module scope: const lib = require('k6/http')","See https://grafana.com/docs/k6/latest/using-k6/test-lifecycle/ for the test lifecycle"],"exampleFix":null,"handlingStrategy":"validation","validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"01ffac6f245854c1b8adc6a69857c76a15f90022","analyzedAt":"2026-08-18T03:05:52.393Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}