NPM Packages and Dependencies

Updated · 8 min read
hardES2026javascriptnpmpackage-jsonsemversecurity

npm is the package manager that comes with Node.js. It installs packages (reusable libraries published by others) from the npm registry, records which ones your project uses in package.json, pins their exact versions in package-lock.json, and runs your project's scripts. Almost every JavaScript project, front end or back end, uses it (or a compatible alternative such as pnpm, Yarn or Bun). Packages save enormous amounts of work, but every package is code written by someone else that runs with your app's permissions, so using them safely matters as much as using them at all.

In One Minute

  • npm init -y creates package.json; npm install name adds a dependency; npm install -D name adds a development-only one.
  • package.json lists dependencies with version ranges; package-lock.json records the exact versions installed. Commit both.
  • npm ci installs exactly what the lock file says: use it in CI and deployments.
  • "scripts" define commands run with npm run name (npm test and npm start are shortcuts).
  • Every dependency is a security decision: check what you add, keep it updated, and run npm audit.

Starting a Project

Terminal
mkdir fee-tracker && cd fee-tracker
npm init -y
npm install date-fns
npm install --save-dev eslint

npm init -y creates a package.json with default values. npm install date-fns downloads the package into node_modules/ and records it under dependencies; --save-dev (or -D) records a tool under devDependencies. The result:

package.json
{
  "name": "fee-tracker",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node src/index.js",
    "test": "node --test",
    "lint": "eslint src"
  },
  "dependencies": {
    "date-fns": "^4.1.0"
  },
  "devDependencies": {
    "eslint": "^9.39.0"
  },
  "engines": {
    "node": ">=26"
  }
}
FieldMeaning
name, versionIdentify the package (required to publish)
type"module" makes .js files ES modules
scriptsNamed commands for npm run
dependenciesPackages the app needs to run
devDependenciesPackages needed only to develop: test runners, linters, build tools
enginesWhich Node.js versions the project supports
main, exportsWhat other code gets when it imports this package (for libraries)
private: truePrevents accidental publishing

Installing and Using Packages

CommandDoes
npm installInstalls everything in package.json (and updates the lock file if needed)
npm ciClean install of exactly the lock file's versions; fails if they disagree
npm install nameAdds a dependency
npm install -D nameAdds a dev dependency
npm install name@4.1.0Installs a specific version
npm uninstall nameRemoves a package
npm updateUpdates packages within their allowed ranges
npm outdatedLists packages with newer versions
npm ls nameShows where a package sits in the dependency tree

Installed packages are imported by name; Node.js finds them in node_modules:

src/index.js
import { format, addDays } from "date-fns";
console.log(format(addDays(new Date(2026, 0, 5), 30), "MM/dd/yyyy"));   // 02/04/2026

Never edit files inside node_modules or commit that folder: it's regenerated by npm install. Add it to .gitignore.

Scripts

npm run <name> runs a script from package.json, with node_modules/.bin on the PATH, so locally installed tools work without a global install:

Terminal
npm run lint        # runs: eslint src
npm test            # shortcut for npm run test
npm start           # shortcut for npm run start
npm run build -- --watch   # arguments after -- are passed to the script

Scripts named pre<name> and post<name> run before and after <name> automatically (for example pretest). Scripts are the place to document how to work on a project: a new teammate only needs npm install and npm test.

Semantic Versioning

Package versions follow semantic versioning (semver): MAJOR.MINOR.PATCH.

PartIncreased whenExample
MAJORBreaking changes3.4.2 → 4.0.0
MINORNew features, backward compatible4.0.0 → 4.1.0
PATCHBug fixes, backward compatible4.1.0 → 4.1.1

package.json usually stores a range, not an exact version:

RangeAllowsFor ^4.1.0 / ~4.1.0
^4.1.0 (caret, the default)Minor and patch updates4.1.0 up to, not including, 5.0.0
~4.1.0 (tilde)Patch updates only4.1.0 up to, not including, 4.2.0
4.1.0Exactly that version4.1.0 only
>=4.1.0Anything newerAny later version, including breaking ones

Versions below 1.0.0 are treated more strictly: ^0.3.2 allows only 0.3.x, because in 0.x versions minor bumps may break things. Here is the caret rule as a small function:

caret.js▶ Try it
function satisfiesCaret(version, range) {
  const [maj, min, pat] = version.split(".").map(Number);
  const [rMaj, rMin, rPat] = range.replace("^", "").split(".").map(Number);
  if (maj !== rMaj) return false;
  if (rMaj === 0 && min !== rMin) return false;
  if (min !== rMin) return min > rMin;
  return pat >= rPat;
}
 
for (const v of ["4.1.0", "4.9.3", "5.0.0", "4.0.9"]) console.log(v, satisfiesCaret(v, "^4.1.0"));
console.log("0.4.0", satisfiesCaret("0.4.0", "^0.3.2"));
Output
4.1.0 true
4.9.3 true
5.0.0 false
4.0.9 false
0.4.0 false

(Real projects use the semver package, which handles prerelease tags and every range form.)

Lock Files

Ranges mean that two installs on different days can get different versions. package-lock.json records the exact version, download URL and integrity hash of every package in the tree, including the dependencies of your dependencies:

PracticeWhy
Commit package-lock.jsonEveryone, and every server, gets the same versions
Use npm ci in CI and deploymentsInstalls exactly the lock file, fails if package.json and the lock disagree, never changes the lock
Review lock file changes in pull requestsA surprising new package or version can be an attack

npx

npx runs a package's command without installing it permanently (or runs a locally installed one):

Terminal
npx prettier --check src     # uses the local prettier if installed, otherwise downloads it
npx create-vite@latest my-app

Supply-Chain Security

Your app runs not only your code but every dependency, and every dependency's dependencies, often hundreds of packages. Attacks on this supply chain are real and frequent: hijacked maintainer accounts publishing malicious updates, typosquatting (reactt instead of react), and malicious install scripts that run during npm install.

DefenseHow
Add dependencies deliberatelyCheck downloads, maintenance, open issues, and whether you really need it; a few lines of your own code may be safer
Pin and lockCommit the lock file; use npm ci
Audit regularlynpm audit lists known vulnerabilities; npm audit fix applies compatible fixes
Update thoughtfullyUse automated update tools (such as Dependabot) and review their changes
Limit install scriptsnpm install --ignore-scripts, or allow scripts only for packages that need them
Verify provenancenpm audit signatures checks registry signatures and provenance attestations
Protect your publishing accountTwo-factor authentication and trusted publishing for packages you maintain
Terminal
npm audit
npm audit --omit=dev      # only what ships to production
npm audit signatures

In Practice

The Fee Tracker's package.json for a small Node.js service: ES modules, documented scripts, a Node.js version requirement, minimal runtime dependencies, and safety settings:

package.json
{
  "name": "fee-tracker-api",
  "version": "1.3.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=26" },
  "scripts": {
    "start": "node src/server.js",
    "dev": "node --watch --env-file=.env src/server.js",
    "test": "node --test",
    "lint": "eslint .",
    "check": "npm run lint && npm test && npm audit --omit=dev"
  },
  "dependencies": {},
  "devDependencies": {
    "eslint": "^9.39.0"
  }
}

This service needs no runtime dependencies at all: Node.js 26 has fetch, a test runner, --watch, .env file loading and Temporal built in. Every dependency avoided is one less thing to audit and update.

Common Mistakes

Committing node_modules. It's huge and machine-specific. Commit package.json and the lock file instead.

Not committing the lock file. Builds become unrepeatable. Commit it.

Using npm install in CI. It can change versions. Use npm ci.

Putting build tools in dependencies. They bloat production installs. Use devDependencies.

Adding packages for trivial tasks. Each one is code you must trust and maintain.

Practice

Challenge: Write parseVersion(v) that splits a semver string into numbers and isBreaking(from, to) that returns true when the major version increases (or, for 0.x, when the minor version increases).

Show solution
breaking.js▶ Try it
const parseVersion = (v) => v.split(".").map(Number);
 
function isBreaking(from, to) {
  const [fMaj, fMin] = parseVersion(from);
  const [tMaj, tMin] = parseVersion(to);
  if (tMaj !== fMaj) return tMaj > fMaj;
  return fMaj === 0 && tMin > fMin;
}
 
console.log(isBreaking("4.1.0", "4.9.0"), isBreaking("4.1.0", "5.0.0"), isBreaking("0.3.2", "0.4.0"));
Output
false true true

Quick check: npm

3 questions
1Where should a test runner be listed?
2Which versions does ^4.1.0 allow?
3Which command should CI use to install dependencies?

Key Takeaways

TaskCommand
New projectnpm init -y
Add a dependencynpm install name
Add a dev toolnpm install -D name
Repeatable installnpm ci
Run a scriptnpm run lint
Check vulnerabilitiesnpm audit

Was this tutorial helpful?

Lesson 113 of 139