Semantic Versioning

Version numbers follow MAJOR.MINOR.PATCH to signal the kind of change.

Syntax"express": "^4.18.2"

npm packages use semantic versioning (semver), a three-part number: MAJOR.MINOR.PATCH.

PartIncreases when
MAJORa breaking change is made
MINORa new feature is added (backward compatible)
PATCHa bug is fixed

Range symbols

  • ^1.2.3 — allow minor and patch updates (1.x.x).
  • ~1.2.3 — allow patch updates only (1.2.x).
  • 1.2.3 — exactly this version.

Example

Example · json
{
  "dependencies": {
    "express": "^4.18.2",
    "chalk": "~5.3.0",
    "left-pad": "1.3.0"
  }
}
// ^4.18.2  -> 4.x.x
// ~5.3.0   -> 5.3.x
// 1.3.0    -> exactly 1.3.0

When to use it

  • A library maintainer bumps the major version from 1.x to 2.x to signal a breaking API change, so dependents' `^1.0.0` ranges keep them on the old version.
  • A DevOps engineer pins a critical dependency with an exact version `"lodash": "4.17.21"` in production to prevent unexpected updates from breaking the build.
  • An automated Dependabot PR updates `^4.0.0` to the latest patch release within the allowed range without requiring a code review.

More examples

Semver range operators

Shows the four common range operators: `^` (compatible), `~` (patch), exact, and wildcard.

Example · json
{
  "dependencies": {
    "express":  "^4.18.2",
    "lodash":   "~4.17.21",
    "uuid":     "9.0.0",
    "dotenv":   "*"
  }
}

Check a version range programmatically

Uses the `semver` npm package to validate and compare version strings programmatically.

Example · js
const semver = require('semver');

semver.satisfies('4.18.2', '^4.0.0'); // true
semver.satisfies('5.0.0',  '^4.0.0'); // false
semver.gt('2.0.0', '1.9.9');          // true
semver.valid('not-a-version');         // null

Bump version with npm

Uses `npm version` to increment the package.json version according to semver rules and create a git tag.

Example · bash
npm version patch   # 1.0.0 -> 1.0.1
npm version minor   # 1.0.1 -> 1.1.0
npm version major   # 1.1.0 -> 2.0.0
# Each command also creates a git tag

Discussion

  • Be the first to comment on this lesson.