← Back to Node.js, page 7

nodejs-0130 · Easy fresher

What does package-lock.json protect you from, and how do you check a lockfile for drift and unsafe entries in CI?

The lockfile records the exact version, download URL and integrity hash of every dependency, so every install gets the same files and a tampered download is rejected. npm ci installs exactly what the lockfile says and fails when package.json and the lockfile disagree. Commit the lockfile, use npm ci in CI and production builds, and review lockfile changes like code.

Full answer

What is in the lockfile

  • For every package (lockfileVersion 3 uses a flat packages map): version, resolved (the tarball URL), integrity (a SHA-512 hash), dependencies and flags such as dev, optional and hasInstallScript.
  • It is a snapshot of the full tree, including transitive dependencies that package.json does not list.

What it gives you

  • Repeatable installs. A caret range in package.json can resolve to a newer version tomorrow. The lockfile pins what you tested.
  • Integrity: npm checks the downloaded file against the hash. A changed or poisoned tarball fails the install.
  • Faster installs and clear diffs for updates.

npm install versus npm ci

  • npm install may update the lockfile when ranges allow newer versions.
  • npm ci deletes node_modules, installs exactly the lockfile, never writes it, and exits with an error if package.json and the lockfile are out of sync. This is the command for CI, Docker builds and deployments.

Hygiene checks in CI

  • Run npm ci, not npm install. Fail the build if the lockfile changes (git diff --exit-code package-lock.json).
  • Review lockfile diffs in pull requests. Watch for resolved URLs that point to unexpected hosts, git or http dependencies, and entries that lose their integrity hash.
  • Use one package manager per repository and commit the lockfile for applications. Libraries commit it too for their own development, even though consumers ignore it.
  • Run npm audit regularly and update with intent (npm update, Renovate or Dependabot), not by deleting the lockfile.
  • Avoid resolving conflicts by hand-editing. Delete the conflict markers by re-running npm install to regenerate the affected entries.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');

// 1. A small lockfile check: registry host, https, and an integrity hash on every package.
const lock = {
  lockfileVersion: 3,
  packages: {
    '': { name: 'app', dependencies: { express: '^5.0.0' } },
    'node_modules/express': { version: '5.1.0', resolved: 'https://registry.npmjs.org/express/-/express-5.1.0.tgz', integrity: 'sha512-AAAA' },
    'node_modules/leftpad': { version: '1.3.0', resolved: 'https://registry.npmjs.org/leftpad/-/leftpad-1.3.0.tgz' },
    'node_modules/tool': { version: '2.0.0', resolved: 'http://example.test/tool-2.0.0.tgz', integrity: 'sha512-BBBB' },
    'node_modules/fork': { version: '0.1.0', resolved: 'git+ssh://git@example.test/fork.git#abc123' },
  },
};
function checkLock(lockfile) {
  const problems = [];
  for (const [location, info] of Object.entries(lockfile.packages)) {
    if (location === '') continue;
    const name = location.replace('node_modules/', '');
    if (!info.integrity) problems.push(`${name}: no integrity hash`);
    if (!/^https:\/\/registry\.npmjs\.org\//.test(info.resolved || '')) problems.push(`${name}: not from the npm registry over https (${info.resolved.split(':')[0]})`);
  }
  return problems;
}
console.log(checkLock(lock).join('\n'));

// 2. npm ci refuses to run when package.json and the lockfile disagree.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lock-'));
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'demo', version: '1.0.0' }));
const npm = (...args) => spawnSync('npm', args, { cwd: dir, encoding: 'utf8' });
npm('install', '--package-lock-only', '--offline', '--no-audit', '--no-fund');
console.log('lockfile created:', fs.existsSync(path.join(dir, 'package-lock.json')));
console.log('npm ci in sync exit code:', npm('ci', '--offline', '--no-audit', '--no-fund').status);
fs.mkdirSync(path.join(dir, 'local-dep'));
fs.writeFileSync(path.join(dir, 'local-dep', 'package.json'), JSON.stringify({ name: 'local-dep', version: '1.0.0' }));
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'demo', version: '1.0.0', dependencies: { 'local-dep': 'file:./local-dep' } }));
const drift = npm('ci', '--offline', '--no-audit', '--no-fund');
console.log('npm ci after adding a dependency without updating the lockfile: exit code', drift.status, '| EUSAGE:', /EUSAGE/.test(drift.stderr));
fs.rmSync(dir, { recursive: true });

The first part is a small checker run on a made-up lockfile. The second part runs the real npm ci in a temporary project, once in sync and once with drift. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): leftpad: no integrity hash tool: not from the npm registry over https (http) fork: no integrity hash fork: not from the npm registry over https (git+ssh) lockfile created: true npm ci in sync exit code: 0 npm ci after adding a dependency without updating the lockfile: exit code 1 | EUSAGE: true

Key points

  • The lockfile pins exact versions, URLs and integrity hashes.
  • Integrity hashes detect tampered downloads.
  • npm ci never changes the lockfile and fails on drift.
  • Review lockfile diffs for odd hosts and missing hashes.
  • Never delete the lockfile to fix a problem.

Common mistakes

  • Deleting package-lock.json and package.json node_modules to fix errors.
  • Using npm install in CI, which can change versions.
  • Approving lockfile changes without reading them.
  • Mixing npm, Yarn and pnpm lockfiles in one repository.
  • Not committing the lockfile for an application.

Follow-ups

  • What is the integrity field, and which algorithm does it use?
  • How do you update one dependency without touching the rest?
  • What does npm ci do to node_modules before installing?

Tips

  • Say 'exact versions plus integrity hashes'.
  • Contrast npm install and npm ci.
  • Mention reviewing the lockfile diff.