{"record":{"id":"50c0eaeca8f6e8e2","repo":"vitest-dev/vitest","slug":"failed-to-load-custom-defines-error-message","errorCode":null,"errorMessage":"Failed to load custom \"defines\": ${error.message}","messagePattern":"Failed to load custom \"defines\": (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/vitest/src/runtime/workers/base.ts","lineNumber":146,"sourceCode":"  const { ctx } = state\n  state.environment = _currentEnvironment\n  state.durations.environment = _environmentTime\n  // state has new context, but we want to reuse existing ones\n  state.evaluatedModules = evaluatedModules\n  state.moduleExecutionInfo = moduleExecutionInfo\n\n  provideWorkerState(globalThis, state)\n\n  // we could load @vite/env, but it would take ~8ms, while this takes ~0,02ms\n  if (state.config.serializedDefines) {\n    try {\n      runInThisContext(`(() =>{\\n${state.config.serializedDefines}})()`, {\n        lineOffset: 1,\n        filename: 'virtual:load-defines.js',\n      })\n    }\n    catch (error: any) {\n      throw new Error(`Failed to load custom \"defines\": ${error.message}`)\n    }\n  }\n\n  if (ctx.invalidates) {\n    ctx.invalidates.forEach((filepath) => {\n      const modules = state.evaluatedModules.fileToModulesMap.get(filepath) || []\n      modules.forEach((module) => {\n        state.evaluatedModules.invalidateModule(module)\n      })\n    })\n  }\n  ctx.files.forEach((i) => {\n    const filepath = i.filepath\n    const modules = state.evaluatedModules.fileToModulesMap.get(filepath) || []\n    modules.forEach((module) => {\n      state.evaluatedModules.invalidateModule(module)\n    })\n  })","sourceCodeStart":128,"sourceCodeEnd":164,"githubUrl":"https://github.com/vitest-dev/vitest/blob/1fa9837ec26533512fdcad8baebf249771bd340a/packages/vitest/src/runtime/workers/base.ts#L128-L164","documentation":"Vitest serializes config.define into a JS expression string (serializedDefines) and runs it via runInThisContext to inject global constants into the worker. If that generated JS fails to parse/evaluate, the original error is caught and re-thrown wrapped as 'Failed to load custom defines: <message>'. This runs in the base (non-vm) worker path.","triggerScenarios":"The define config produces values whose JSON serialization is not valid as the body of an IIFE in the worker context — e.g. a function, a circular object, a BigInt, or a value whose custom toJSON returns something unparseable. runInThisContext throws SyntaxError or TypeError, which gets wrapped.","commonSituations":"Putting non-serializable values in vitest.config define (functions, class instances, symbols), or a plugin mutating define at runtime to inject something that is not plain JSON.","solutions":["Ensure every define value is JSON-serializable (strings, numbers, booleans, plain objects/arrays).","Avoid functions, BigInt, circular references, and Symbols in test.define / vite.define.","Read the wrapped error.message (the inner exception) to identify which define key broke.","If you need runtime values, import them from a module instead of inlining via define."],"exampleFix":"// before\nexport default defineConfig({\n  test: { define: { __fn: () => 1 } }\n})\n\n// after\nexport default defineConfig({\n  test: { define: { __flag: JSON.stringify('on') } }\n})","handlingStrategy":"validation","validationCode":"import { isJSON } from './checks'\nfunction validateDefines(obj) {\n  for (const [k, v] of Object.entries(obj)) {\n    try { JSON.parse(JSON.stringify(v)) } catch { throw new Error(`define '${k}' is not serializable`) }\n  }\n}","typeGuard":"function isJsonSerializable(v) {\n  try { JSON.stringify(v); return true } catch { return false }\n}","tryCatchPattern":null,"preventionTips":["Keep define values to primitives and plain JSON structures.","Avoid functions, BigInt, Symbols, and circular refs in define.","Validate the serializedDefines string during config build."],"tags":["config","define","serialization","worker"],"backgroundTag":null,"analyzedSha":"1fa9837ec26533512fdcad8baebf249771bd340a","analyzedAt":"2026-08-11T16:11:39.638Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}