Skip to main content

Security and hardening · Beginner · 20 min

Audit Node.js dependencies with npm audit and fix them safely

By Padding · Updated 18 Nov 2026
node:26 image (Debian) · Node.js 26.13.1 · npm 11.20.0

You will read an npm audit report for a project with three vulnerable dependencies, fix each one the right way (a compatible update, a deliberate major upgrade and an override), gate CI on what ships, keep a dated exceptions file and check registry signatures.

On this page

Most of the code in a Node.js app is code you did not write. A project with ten direct dependencies can easily install a few hundred packages, and any of them can have a published security advisory. npm audit is the check that comes with npm: it sends the names and versions in your lockfile to the registry, gets back the advisories that match, and works out what would fix each one.

The tool takes one command to run and not much more to misuse. npm audit fix --force will happily install a new major version of a package your code depends on, and a green audit in CI says nothing about the advisory someone silenced six months ago. In this tutorial you build a small throwaway project with three real, published vulnerabilities, each needing a different fix:

  • a direct dependency with a fix inside its allowed version range, which npm audit fix handles
  • a direct dependency whose only fix is a new major version, which you upgrade on purpose and test
  • a vulnerable package pulled in by another package that has no fixed release, which you fix with an override

On the way you read the report properly, separate what ships from what only runs on your machine, make CI fail at the right severity, keep a short exceptions file with reasons and expiry dates, and check that what you installed is what the registry published. Everything happens in ~/npm-audit-demo, which you delete at the end.

Step 1 · Build a project with known vulnerabilities

The project needs a package that pins an old dependency and has no newer release, the situation where overrides earn their keep. Rather than depend on someone's abandoned package, you make a tiny stand-in called legacy-reporter. It pins lodash 4.17.20 exactly, the way old internal tools often do, and sorts a list of names with it. Create it and pack it into a tarball, so npm installs it like any registry package:

Bash
mkdir -p ~/npm-audit-demo/legacy-reporter ~/npm-audit-demo/app
cd ~/npm-audit-demo/legacy-reporter
cat > package.json <<'JSON'
{
  "name": "legacy-reporter",
  "version": "1.0.0",
  "description": "Stand-in for an unmaintained package that pins an old lodash",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "lodash": "4.17.20"
  }
}
JSON
cat > index.js <<'JS'
const sortBy = require('lodash/sortBy')
module.exports = (rows) => sortBy(rows, 'name').map((row) => row.name).join(', ')
JS
npm pack

Now the app. It uses jsonwebtoken to issue and check sign-in tokens and minimist to parse command-line flags, both at old versions with published advisories. legacy-reporter goes in as a development dependency, a tool you use while building rather than code that ships:

Bash
cd ~/npm-audit-demo/app
npm init -y > /dev/null
npm pkg set type=module scripts.test="node --test"
npm install minimist@1.2.5 jsonwebtoken@8.5.1
npm install --save-dev ../legacy-reporter/legacy-reporter-1.0.0.tgz

Each npm install ends with a line such as found 4 vulnerabilities: npm runs a quick audit after every install, but installs anyway.

Before you change any dependency, you need a way to tell whether the change broke something. Add a small token module and two tests for it. The module reads its signing secret from the TOKEN_SECRET environment variable, never from the code; the tests set a random throwaway secret for their own run:

Bash
cat > token.js <<'JS'
import jwt from 'jsonwebtoken'

function secret() {
  const value = process.env.TOKEN_SECRET
  if (!value) throw new Error('Set TOKEN_SECRET in the environment')
  return value
}

export function issue(user) {
  return jwt.sign({ sub: user }, secret(), { algorithm: 'HS256', expiresIn: '15m' })
}

export function check(token) {
  return jwt.verify(token, secret(), { algorithms: ['HS256'] })
}
JS
mkdir -p test
cat > test/token.test.js <<'JS'
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { randomBytes } from 'node:crypto'
import { issue, check } from '../token.js'

// A throwaway secret for this test run only.
process.env.TOKEN_SECRET = randomBytes(32).toString('hex')

test('a token the app issued is accepted', () => {
  assert.equal(check(issue('ada')).sub, 'ada')
})

test('an unsigned token is refused', () => {
  const part = (value) => Buffer.from(JSON.stringify(value)).toString('base64url')
  const unsigned = `${part({ alg: 'none', typ: 'JWT' })}.${part({ sub: 'ada' })}.`
  assert.throws(() => check(unsigned))
})
JS
npm test

Check it worked

Bash
npm ls --all minimist jsonwebtoken lodash

The tree shows jsonwebtoken@8.5.1 and minimist@1.2.5 at the top level and lodash@4.17.20 under legacy-reporter@1.0.0. npm test ended with pass 2 and fail 0 in its summary.

Step 2 · Read the audit report

Run the audit:

Bash
npm audit

The report has one block per vulnerable package. The minimist block looks something like this:

Text
minimist  1.0.0 - 1.2.5
Severity: critical
Prototype Pollution in minimist - https://github.com/advisories/GHSA-xvch-5gv4-984h
fix available via `npm audit fix`
node_modules/minimist

Read each block in the same order:

  • Package and vulnerable range. minimist 1.0.0 - 1.2.5 means every version in that range is affected. Compare it with what you have installed.
  • Severity. One of low, moderate, high or critical, taken from the advisory. It describes the flaw in general, not how exposed your app is: a critical flaw in a function you never call matters less than a moderate one on your login route.
  • Advisory. A title and a link to the GitHub Advisory Database. The GHSA-... part of the link is the advisory's ID; you will use it later.
  • Fix. fix available via npm audit fix means a fixed version fits the range in your package.json. The jsonwebtoken block instead says fix available via npm audit fix --force and Will install jsonwebtoken@9.0.3, which is a breaking change. The lodash block says No fix available.
  • Path. node_modules/lodash is where it sits, and the indented legacy-reporter ... Depends on vulnerable versions of lodash lines name the package that pulled it in.

The last line counts vulnerabilities by severity. The count includes legacy-reporter itself, because a package that depends on a vulnerable package is reported too.

For anything larger than this project, the JSON report is easier to work with. npm audit exits with code 1 when it finds anything, so || true keeps the command from stopping a script. Save the report and print one line per package:

Bash
npm audit --json > audit.json || true
node -e '
const report = require("./audit.json")
for (const v of Object.values(report.vulnerabilities)) {
  const f = v.fixAvailable
  const fix = f === true ? "npm audit fix" : f ? `${f.name}@${f.version}${f.isSemVerMajor ? " (major)" : ""}` : "none"
  console.log(v.name.padEnd(16), v.severity.padEnd(9), (v.isDirect ? "direct" : "transitive").padEnd(11), fix)
}'

To see why a package is installed at all, ask npm to explain it:

Bash
npm explain lodash

Check it worked

The summary prints four lines, something like:

Text
jsonwebtoken     high      direct      jsonwebtoken@9.0.3 (major)
legacy-reporter  high      direct      none
lodash           high      transitive  none
minimist         critical  direct      npm audit fix

npm explain lodash starts with lodash@4.17.20 dev and shows where it came from: lodash@"4.17.20" from legacy-reporter@1.0.0.

Step 3 · Apply the fixes that stay in range

npm audit fix only installs versions allowed by the ranges in package.json. When you ran npm install minimist@1.2.5, npm saved the range ^1.2.5, which allows any later 1.x release, so a fixed version fits:

Bash
npm audit fix || echo "npm audit fix exited with code $? because some findings remain"
npm test

The command updates package-lock.json and node_modules. It leaves the jsonwebtoken and lodash findings alone and says so: the summary still lists them, with the advice to try --force. It also exits with code 1, because it fixes a project only partly; the message after || says so instead of leaving you to guess.

Check it worked

Bash
npm ls minimist
npm pkg get dependencies.minimist

npm ls shows minimist@1.2.8 (or a later 1.x release), while package.json still says "^1.2.5". The range did not need to change; the lockfile now records the fixed version, and every npm ci installs that one. Commit both files together. The tests still pass.

Step 4 · Upgrade a major version on purpose

The jsonwebtoken advisories are fixed only in version 9, and a new major version is allowed to change behaviour your code relies on. npm audit fix --force would install it without asking, along with any other major changes it finds. Preview what it would do instead:

Bash
npm audit fix --force --dry-run

The output starts with warnings such as Updating jsonwebtoken to 9.0.3, which is a SemVer major change and lists every package it would change. On a real project this list can include majors of several packages at once, and the change lands in one commit with no hint of which one broke your build. That is why you upgrade majors one at a time, by name.

Read the upgrade notes first. jsonwebtoken's v8 to v9 migration notes list what changed, such as stricter checks on key types and RSA key sizes. This app signs with an HMAC secret and already passes an explicit algorithms list to verify, so the notes suggest it should be unaffected. The tests decide. Install the new major and run them:

Bash
npm install jsonwebtoken@9.0.3
npm test

Installing a named version writes the new range, ^9.0.3, to package.json. If a test failed here, you would fix the code or stay on version 8 and record an exception (step 6) while you work on it, not ship a broken build.

Check it worked

Bash
npm ls jsonwebtoken
npm audit --omit=dev

npm ls shows jsonwebtoken@9.0.3, the tests report pass 2, and the production-only audit prints found 0 vulnerabilities.

Step 5 · Gate CI on the right findings

Only lodash is left, and it arrived through a development tool. --omit=dev audits only the packages that ship with the app, which you just saw come back clean. The full audit still fails:

Bash
for level in critical high; do
  if npm audit --audit-level="$level" > /dev/null; then
    echo "--audit-level=$level: pass"
  else
    echo "--audit-level=$level: fail"
  fi
done

--audit-level sets the lowest severity that makes the command exit with a non-zero code. It does not hide anything from the report; the lodash findings are still printed, they only stop failing the build at the critical threshold.

Do not drop development dependencies from your checks altogether. Build tools and test runners run on developer laptops and in CI, where there are tokens and secrets worth stealing. A sensible split is a strict gate on what ships, and a report on everything that someone reads. Save both as scripts, so CI and people run the same commands:

Bash
npm pkg set "scripts.audit:ship=npm audit --omit=dev --audit-level=high"
npm pkg set "scripts.audit:all=npm audit"
npm run audit:ship

In CI, install with npm ci and then run npm run audit:ship as a step that fails the job. On a slow or prepaid connection, npm audit --package-lock-only audits straight from the lockfile without installing anything, so you can check a project before you spend data downloading it.

Check it worked

The loop prints --audit-level=critical: pass and --audit-level=high: fail. npm run audit:ship exits with code 0 and prints found 0 vulnerabilities.

Step 6 · Keep a short exceptions file

Sometimes you cannot fix a finding today: the parent package has no release, or the upgrade needs a week of work. npm has no built-in way to accept one advisory, so teams often loosen --audit-level or turn the check off, and then nobody remembers why. A small exceptions file is better. Each entry names the package and the exact advisory IDs, says why the risk is acceptable for now, who owns it and when it must be looked at again.

The gate script below runs npm audit --json and checks every advisory against that file. An advisory not listed blocks the build, an exception past its date blocks the build, and an exception that no longer matches anything is reported as stale so you delete it. It uses execFileSync, which runs npm without a shell; it is written for macOS and Linux. Create it:

Bash
mkdir -p scripts
cat > scripts/audit-gate.mjs <<'JS'
// Fail on any npm audit advisory that is not listed, with a reason and a date, in audit-exceptions.json.
import { execFileSync } from 'node:child_process'
import { readFileSync } from 'node:fs'

const today = process.env.AUDIT_TODAY ?? new Date().toISOString().slice(0, 10)
const exceptions = JSON.parse(readFileSync('audit-exceptions.json', 'utf8'))

let raw
try {
  raw = execFileSync('npm', ['audit', '--json'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] })
} catch (err) {
  raw = err.stdout // npm audit exits 1 when it finds anything; the report is still on stdout
}
const report = JSON.parse(raw)
if (report.error) {
  console.error(`npm audit could not run: ${report.error.summary}`)
  process.exit(2)
}

const found = new Map()
for (const vuln of Object.values(report.vulnerabilities)) {
  for (const via of vuln.via) {
    if (typeof via === 'string') continue // "via another package", which has its own entry
    found.set(via.url.split('/').pop(), { pkg: via.name, severity: via.severity, title: via.title })
  }
}

let failed = false
for (const [id, { pkg, severity, title }] of found) {
  const entry = exceptions.find((e) => e.package === pkg && e.advisories.includes(id))
  if (!entry) {
    console.log(`BLOCK   ${id} ${pkg} (${severity}): ${title}`)
    failed = true
  } else if (!entry.reason || !entry.owner || !entry.expires) {
    console.log(`INVALID ${id} ${pkg}: an exception needs a reason, an owner and an expiry date`)
    failed = true
  } else if (entry.expires < today) {
    console.log(`EXPIRED ${id} ${pkg}: the exception ran out on ${entry.expires}; review it again`)
    failed = true
  } else {
    console.log(`ALLOW   ${id} ${pkg} until ${entry.expires}: ${entry.reason}`)
  }
}
for (const entry of exceptions) {
  for (const id of entry.advisories) {
    if (!found.has(id)) console.log(`STALE   ${id} ${entry.package}: no longer reported; delete it`)
  }
}
console.log(failed ? 'Audit gate: FAIL' : 'Audit gate: PASS')
process.exitCode = failed ? 1 : 0
JS
npm pkg set "scripts.audit:gate=node scripts/audit-gate.mjs"

Start with an empty exceptions file and run the gate. It fails, and the BLOCK lines give you the IDs to review:

Bash
echo '[]' > audit-exceptions.json
npm run audit:gate || echo "The gate failed with exit code $?"

You have read the lodash advisories: they affect _.template, _.unset, _.omit, _.pullAt and some string functions, and legacy-reporter only calls sortBy on names you supply, on your own machine. That is a reasonable case for a short exception while you fix it properly. Write the file. In your own projects you type the expiry date; here the node -p part fills in a date 30 days from today:

Bash
cat > audit-exceptions.json <<JSON
[
  {
    "package": "lodash",
    "advisories": [
      "GHSA-35jh-r3h4-6jhm",
      "GHSA-29mw-wpgm-hmr9",
      "GHSA-r5fr-rjxr-66jc",
      "GHSA-xxjr-mmjv-4gpg"
    ],
    "reason": "Dev-only, via legacy-reporter, which calls only sortBy on our own data. No fixed release; override planned.",
    "owner": "replace this with your name or team",
    "added": "$(node -p 'new Date().toISOString().slice(0, 10)')",
    "expires": "$(node -p 'new Date(Date.now() + 30 * 864e5).toISOString().slice(0, 10)')"
  }
]
JSON
npm run audit:gate

Keep the file in the repository, next to package.json, so every change to an exception goes through review like code. Keep it short: thirty days, not a year, and one entry per decision.

Check it worked

The first run printed four BLOCK lines for lodash, Audit gate: FAIL and The gate failed with exit code 1. The second prints four ALLOW lines with the expiry date and Audit gate: PASS. To see what happens when the date passes, pretend it is 2099:

Bash
AUDIT_TODAY=2099-01-01 npm run audit:gate || echo "The gate failed with exit code $?"

Every lodash line now reads EXPIRED, and the gate fails again.

Step 7 · Fix a transitive dependency with an override

legacy-reporter will never get a new release, so its lodash pin will never move. An override tells npm to use a version you choose for a package anywhere in the tree, whatever its parents ask for. Overrides live only in the top-level package.json of your project. Point lodash at the current fixed release:

Bash
npm pkg set overrides.lodash=4.18.1
npm install
npm ls --all lodash

An override forces a version the parent's authors never tested with, so test the code that uses it. lodash 4.18 is a minor release of the same major, which keeps the risk low, but check anyway:

Bash
node -e 'const report = require("legacy-reporter"); console.log(report([{ name: "Zainab" }, { name: "Amara" }, { name: "Kofi" }]))'
npm test

Then run the gate:

Bash
npm run audit:gate

The four lodash exceptions are now reported as STALE. Delete the entry, so the file holds only decisions that still matter:

Bash
echo '[]' > audit-exceptions.json
npm run audit:gate

Review overrides as often as exceptions. Each one is a promise to drop it when the parent ships a fix or you replace the parent, and an exact pin such as 4.18.1 does not pick up the next security release on its own. Add a line about why it exists to the pull request that adds it.

Check it worked

npm ls --all lodash shows lodash@4.18.1 overridden under legacy-reporter@1.0.0. The reporter prints Amara, Kofi, Zainab, the tests pass, and the last gate run prints only Audit gate: PASS. npm audit now prints found 0 vulnerabilities:

Bash
npm audit

Step 8 · Check registry signatures and provenance

An audit checks versions against advisories. It does not check that the files on your disk are the ones the registry published. The public npm registry signs every package version, and many packages now also publish a provenance attestation: a signed record of the source repository and build that produced them. npm audit signatures checks both for everything in node_modules:

Bash
npm audit signatures

The output reads something like 17 packages have verified registry signatures, and may add a line such as 1 package has a verified attestation. Packages from outside a registry, such as the local legacy-reporter tarball, have no registry signature to check. If a signature does not match, the command names the package and exits with a non-zero code; treat that as a reason to stop and investigate, not to retry until it passes. npm's documentation advises running a recent npm for attestation checks, which can mean updating npm beyond the version bundled with Node.js.

Add it to CI after npm ci, next to the audit gate:

Bash
npm pkg set "scripts.audit:signatures=npm audit signatures"
npm pkg get scripts

Check it worked

npm audit signatures exits with code 0 and reports verified registry signatures. npm pkg get scripts lists test, audit:ship, audit:all, audit:gate and audit:signatures, the five commands a CI job for this project would run.

Next steps

You fixed three advisories three different ways and built a gate that keeps silenced findings visible. When you are done, delete the demo, which removes the old packages with it:

Bash
cd ~
rm -rf ~/npm-audit-demo

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.