Why must package-lock.json be committed to Git?

BeginnerConceptNode.js builds (npm, package.json)
Answer

Short answer

Because it records the exact version of every package in the dependency tree (often hundreds). Without it, ^4.19.2 in package.json could install 4.19.2 today and 4.21.0 next month, and the dependencies of your dependencies can change too — so builds become unpredictable.

Example of what goes wrong without it

  • Monday: CI installs some-lib 2.3.1. Tests pass.
  • Thursday: some-lib 2.4.0 is published with a bug. CI installs it. Builds fail — but nobody changed any code.

What the lockfile contains

"node_modules/express": {
  "version": "4.19.2",
  "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz",
  "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q=="
}

The integrity hash also protects you: if a package's contents change, npm refuses to install it.

What to say in the interview

"The lockfile pins the full resolved tree with integrity hashes, so every install is identical and tamper-evident. We commit it and use npm ci so CI fails if someone forgets to update it."

All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: Node.js apps: npm & package.json

More on Node.js builds (npm, package.json)