Skip to content

/errors/semver/typeerror-invalid-version

TypeError: Invalid Version (semver / npm)

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated
tool
SemVer
exit code
1
versions
semver (npm) 7, npm 9+
os
any

TypeError: Invalid Version: 1.0 comes from the semver package (which npm uses) when a string that is not a valid Semantic Version is parsed as one. SemVer requires exactly three numbers, MAJOR.MINOR.PATCH, so 1.0, 1, 01.2.3 or an empty string are rejected. Fix the version (1.0.0), or validate and normalise input with semver.valid() and semver.coerce() before comparing.

Reproduce it

bash
npm init -y >/dev/null
npm install --silent --no-audit --no-fund semver@7 >/dev/null 2>&1
cat > check.js <<'EOF'
const semver = require("semver");
for (const v of ["1.0", "01.2.3", "v1.2.3", "1.2.3"]) {
  try {
    new semver.SemVer(v);
    console.log(JSON.stringify(v), "-> ok");
  } catch (e) {
    console.log(JSON.stringify(v), "->", `${e.name}: ${e.message}`);
  }
}
console.log("valid('1.0'):", semver.valid("1.0"));
console.log("coerce('1.0'):", semver.coerce("1.0").version);
console.log("clean(' =v1.2.3 '):", semver.clean(" =v1.2.3 "));
EOF
node check.js

Output

"1.0" -> TypeError: Invalid Version: 1.0
"01.2.3" -> TypeError: Invalid Version: 01.2.3
"v1.2.3" -> ok
"1.2.3" -> ok
valid('1.0'): null
coerce('1.0'): 1.0.0
clean(' =v1.2.3 '): 1.2.3

A leading v is accepted and stripped; a missing patch number or a leading zero is not.

Validate before comparing

js
const semver = require("semver");
function newer(a, b) {
  const va = semver.valid(semver.coerce(a));
  const vb = semver.valid(semver.coerce(b));
  if (!va || !vb) throw new Error(`not a version: ${a} / ${b}`);
  return semver.gt(va, vb);
}

coerce() takes the first major[.minor[.patch]] it finds ("v2" becomes 2.0.0, "release-1.4" becomes 1.4.0) and drops pre-release tags unless you pass { includePrerelease: true }.

When npm prints it

If npm install or npm ls fails with npm error Invalid Version: and no version after the colon, a package.json somewhere in the tree has an empty or invalid version. Check your own package.json first, then the package named in the debug log (npm install --loglevel verbose). Reinstalling from a clean state usually removes a corrupted copy:

bash
rm -rf node_modules package-lock.json
npm install

Sources