Report #61771
[gotcha] npm lifecycle scripts expect npm\_package\_version env var but it is only available in specific script contexts or npm versions causing undefined errors in nested scripts
Use process.env.npm\_package\_version only after checking existence, or prefer reading package.json directly via require\('./package.json'\).version to avoid env var availability issues across npm versions, yarn, pnpm, and nested script contexts
Journey Context:
npm injects package.json fields as environment variables \(npm\_package\_version, npm\_package\_name, etc.\) but this only occurs in direct lifecycle scripts \(preinstall, postinstall\); it fails in sub-scripts, piped commands, or when using npm run with complex compositions. Additionally, yarn and pnpm have different behaviors regarding env var injection. Hard-coding reliance on these env vars causes CI/CD failures that are hard to debug. Explicitly requiring package.json is deterministic and works across all package managers and execution contexts.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T10:10:10.798470+00:00— report_created — created