DEV Community

Cover image for NPM Under the Hood: How Dependency Management, Lockfiles, Workspaces, Publishing & Security Really Work
Abanoub Kerols
Abanoub Kerols

Posted on

NPM Under the Hood: How Dependency Management, Lockfiles, Workspaces, Publishing & Security Really Work


Most JavaScript developers know how to use NPM:

npm install express
npm install
npm run dev
npm publish
Enter fullscreen mode Exit fullscreen mode

But knowing these commands is very different from understanding what NPM is actually doing.

When you run:

npm install
Enter fullscreen mode Exit fullscreen mode

NPM is not simply downloading some files.

It is solving a dependency graph, resolving versions, communicating with a registry, validating package metadata, building an installation tree, generating or updating a lockfile, running lifecycle scripts, and storing packages in a local cache.

And when you run:

npm publish
Enter fullscreen mode Exit fullscreen mode

you are not simply uploading a folder.

You are creating a versioned package artifact that can become a dependency of thousands of other applications.

Understanding these internals changes how you think about:

  • package.json
  • package-lock.json
  • semantic versioning
  • dependency conflicts
  • node_modules
  • npm scripts
  • workspaces
  • package publishing
  • security
  • performance
  • reproducible builds

Let's go under the hood.


1. What Is NPM Actually?

First, an important distinction.

npm can refer to several related things:

  1. The npm CLI
  2. The npm Registry
  3. The npm package ecosystem

The CLI is the tool you run:

npm install
Enter fullscreen mode Exit fullscreen mode

The registry is where packages are published and downloaded from.

The ecosystem is the enormous collection of JavaScript packages distributed through npm.

Conceptually:

Your Project
     |
     v
 npm CLI
     |
     +--------------------+
     |                    |
     v                    v
Local Cache           npm Registry
     |                    |
     v                    v
node_modules         Package Metadata
                          +
                       Tarball
Enter fullscreen mode Exit fullscreen mode

The CLI is therefore the bridge between your project and the package registry.


2. What Happens When You Run npm install?

Consider:

npm install express
Enter fullscreen mode Exit fullscreen mode

A simplified view is:

npm install express
        |
        v
Read package.json
        |
        v
Resolve package
        |
        v
Query registry
        |
        v
Resolve dependencies
        |
        v
Build dependency tree
        |
        v
Download package artifacts
        |
        v
Verify integrity
        |
        v
Extract packages
        |
        v
Run lifecycle scripts
        |
        v
Update package-lock.json
Enter fullscreen mode Exit fullscreen mode

There is much more happening than:

"Download Express."


3. The Dependency Graph

Suppose your project contains:

my-app
 |
 +-- express
 |
 +-- mongoose
 |
 +-- jsonwebtoken
Enter fullscreen mode Exit fullscreen mode

But these packages have their own dependencies.

You may actually have something like:

my-app
├── express
│   ├── body-parser
│   ├── cookie
│   ├── debug
│   └── ...
│
├── mongoose
│   ├── mongodb
│   ├── mpath
│   └── ...
│
└── jsonwebtoken
    ├── jws
    ├── jwa
    └── ...
Enter fullscreen mode Exit fullscreen mode

This is a dependency graph.

The difficult part is that dependencies themselves can depend on other dependencies.

For example:

A
├── B
│   └── D
└── C
    └── D
Enter fullscreen mode Exit fullscreen mode

NPM needs to determine which version of D can satisfy both B and C.


4. Why Dependency Resolution Is Hard

Imagine:

Application
├── Package A
│   └── lodash ^4.17.0
│
└── Package B
    └── lodash ^4.18.0
Enter fullscreen mode Exit fullscreen mode

NPM needs to find a version satisfying both ranges.

If:

^4.18.0
Enter fullscreen mode Exit fullscreen mode

and:

^4.17.0
Enter fullscreen mode Exit fullscreen mode

overlap, one compatible version may be installed and shared.

But consider:

Package A
└── lodash ^3.10.0

Package B
└── lodash ^4.17.0
Enter fullscreen mode Exit fullscreen mode

Now the ranges may not overlap.

NPM may need multiple versions.

Conceptually:

node_modules/
├── lodash/              # v4
│
└── package-a/
    └── node_modules/
        └── lodash/      # v3
Enter fullscreen mode Exit fullscreen mode

This is one reason node_modules can become complicated.


5. package.json Is Not the Installation

One of the most important concepts:

package.json
Enter fullscreen mode Exit fullscreen mode

does not describe exactly what is installed.

Instead, it usually describes what your project allows.

For example:

{
  "dependencies": {
    "express": "^5.1.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

This means approximately:

Install a compatible version of Express within the specified semver range.

It does not necessarily mean:

Always install exactly 5.1.0
Enter fullscreen mode Exit fullscreen mode

That's where lockfiles become important.


6. package-lock.json: The Installation Snapshot

Suppose:

"express": "^5.1.0"
Enter fullscreen mode Exit fullscreen mode

Today, NPM might install:

5.1.2
Enter fullscreen mode Exit fullscreen mode

Later:

5.2.0
Enter fullscreen mode Exit fullscreen mode

could potentially satisfy the range.

Without a lockfile, different installations could produce different dependency trees.

The lockfile records the resolved dependency tree.

Conceptually:

package.json
     |
     | allowed versions
     v
Dependency Resolver
     |
     v
package-lock.json
     |
     | exact resolved packages
     v
node_modules
Enter fullscreen mode Exit fullscreen mode

This is why you normally commit:

package-lock.json
Enter fullscreen mode Exit fullscreen mode

to version control for applications.


7. Why Lockfiles Matter

Imagine a team:

Developer A
    |
    v
npm install
    |
    v
Dependency tree A


Developer B
    |
    v
npm install
    |
    v
Dependency tree B
Enter fullscreen mode Exit fullscreen mode

If dependency resolution changes between installations, subtle bugs can appear.

A lockfile makes the installation much more deterministic:

package.json
       +
package-lock.json
       |
       v
same dependency graph
Enter fullscreen mode Exit fullscreen mode

This is especially important in CI/CD.


8. npm install vs npm ci

These commands are often confused.

npm install

Designed for normal development.

It may:

  • resolve dependencies
  • modify package-lock.json
  • install packages
  • update dependency metadata

npm ci

Designed primarily for clean, reproducible installations.

Typical CI pipeline:

npm ci
npm test
npm run build
Enter fullscreen mode Exit fullscreen mode

Conceptually:

package-lock.json
       |
       v
Exact dependency tree
       |
       v
Clean installation
Enter fullscreen mode Exit fullscreen mode

A typical CI workflow therefore prefers:

npm ci
Enter fullscreen mode Exit fullscreen mode

rather than:

npm install
Enter fullscreen mode Exit fullscreen mode

9. The NPM Registry

When you run:

npm install express
Enter fullscreen mode Exit fullscreen mode

NPM needs package information.

By default, the ecosystem uses the public npm registry.

The registry contains metadata describing packages and versions.

Conceptually:

GET package metadata
        |
        v
Find version
        |
        v
Get distribution information
        |
        v
Download package tarball
Enter fullscreen mode Exit fullscreen mode

A package published to npm is essentially distributed as an artifact.

The registry does not magically execute your package.

It stores and serves package information and package artifacts.


10. What Is Actually Inside an NPM Package?

A published package can contain things like:

package/
├── package.json
├── README.md
├── LICENSE
├── dist/
│   ├── index.js
│   └── index.d.ts
└── ...
Enter fullscreen mode Exit fullscreen mode

But you don't necessarily want to publish everything in your repository.

For example:

project/
├── src/
├── tests/
├── .git/
├── .env
├── screenshots/
├── dist/
└── package.json
Enter fullscreen mode Exit fullscreen mode

Publishing the entire repository would be a terrible idea.

NPM therefore provides mechanisms for controlling package contents.


11. npm pack: See What You're Actually Publishing

Before publishing:

npm pack --dry-run
Enter fullscreen mode Exit fullscreen mode

is extremely useful.

It lets you inspect which files would be included.

You can also create the package artifact:

npm pack
Enter fullscreen mode Exit fullscreen mode

You'll get something conceptually like:

my-package-1.0.0.tgz
Enter fullscreen mode Exit fullscreen mode

That .tgz is essentially the package artifact distributed through the registry.

This is a very useful mental model:

Source Repository
       |
       v
npm pack
       |
       v
package.tgz
       |
       v
npm publish
       |
       v
Registry
Enter fullscreen mode Exit fullscreen mode

12. files in package.json

You can control published files:

{
  "files": [
    "dist",
    "README.md",
    "LICENSE"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Now your package can intentionally expose only the important artifacts.

For libraries, this is extremely useful.

A common structure is:

my-package/
├── src/
├── dist/
├── tests/
├── package.json
└── README.md
Enter fullscreen mode Exit fullscreen mode

And publish:

dist/
README.md
LICENSE
package.json
Enter fullscreen mode Exit fullscreen mode

rather than the entire development repository.


13. .npmignore

Another mechanism is:

.npmignore
Enter fullscreen mode Exit fullscreen mode

which can exclude files from the published package.

However, package inclusion rules can become confusing when combining:

files
.npmignore
.gitignore
Enter fullscreen mode Exit fullscreen mode

For package authors, explicitly defining:

"files": ["dist"]
Enter fullscreen mode Exit fullscreen mode

is often a clearer strategy.

Always verify with:

npm pack --dry-run
Enter fullscreen mode Exit fullscreen mode

Never assume.


14. Package Entry Points

Suppose you publish:

my-library
Enter fullscreen mode Exit fullscreen mode

How does another application know what file to load?

Historically:

{
  "main": "dist/index.js"
}
Enter fullscreen mode Exit fullscreen mode

Modern packages often use:

{
  "exports": {
    ".": "./dist/index.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

For example:

{
  "name": "my-library",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": "./dist/index.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

Then:

import { hello } from "my-library";
Enter fullscreen mode Exit fullscreen mode

can resolve to:

dist/index.js
Enter fullscreen mode Exit fullscreen mode

15. Why exports Is Powerful

Consider:

my-library/
├── dist/
│   ├── index.js
│   ├── internal.js
│   └── secret.js
Enter fullscreen mode Exit fullscreen mode

Without proper package boundaries, consumers may attempt:

import x from "my-library/dist/internal.js";
Enter fullscreen mode Exit fullscreen mode

The exports field allows you to define the public API:

{
  "exports": {
    ".": "./dist/index.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

Now your package effectively says:

This is the supported public entry point.

This is extremely important for library design.


16. Conditional Exports

Modern packages can provide different entry points depending on the environment.

For example:

{
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Now:

import library from "my-library";
Enter fullscreen mode Exit fullscreen mode

can resolve differently from:

const library = require("my-library");
Enter fullscreen mode Exit fullscreen mode

This is part of the modern ESM/CommonJS interoperability story.


17. Dependencies vs DevDependencies

Consider:

{
  "dependencies": {
    "express": "^5.1.0"
  },
  "devDependencies": {
    "typescript": "^5.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

The distinction is conceptual:

dependencies

Needed by the package/application at runtime.

devDependencies

Needed to develop, test, lint, or build the project.

For a library:

Your Library
   |
   +-- runtime dependency
   |      └── dependency
   |
   +-- development tooling
          ├── TypeScript
          ├── Vitest
          └── ESLint
Enter fullscreen mode Exit fullscreen mode

18. Peer Dependencies

Peer dependencies are particularly important for libraries.

Imagine you're creating:

react-awesome-button
Enter fullscreen mode Exit fullscreen mode

Your package should work with the consumer's React installation.

You might define:

{
  "peerDependencies": {
    "react": "^18.0.0 || ^19.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

This means:

The application using this library is expected to provide a compatible React version.

This avoids blindly bundling another React installation into the library dependency tree.


19. Optional Dependencies

Sometimes a package can use a dependency if available but doesn't strictly require it.

Example:

{
  "optionalDependencies": {
    "some-platform-specific-package": "^1.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

This is useful for platform-specific behavior.

For example:

Linux
 └── native implementation A

Windows
 └── native implementation B
Enter fullscreen mode Exit fullscreen mode

The installation can tolerate the optional dependency not being available.


20. Semantic Versioning

NPM's dependency management depends heavily on Semantic Versioning, usually called SemVer.

A version:

MAJOR.MINOR.PATCH
Enter fullscreen mode Exit fullscreen mode

For example:

3.7.2
Enter fullscreen mode Exit fullscreen mode

means:

3 = major
7 = minor
2 = patch
Enter fullscreen mode Exit fullscreen mode

The general idea:

MAJOR
breaking changes

MINOR
backward-compatible features

PATCH
backward-compatible fixes
Enter fullscreen mode Exit fullscreen mode

21. The ^ Operator

Consider:

"express": "^5.1.0"
Enter fullscreen mode Exit fullscreen mode

The ^ generally means:

Allow compatible versions according to SemVer rules.

For a normal major version:

^5.1.0
Enter fullscreen mode Exit fullscreen mode

roughly permits:

>=5.1.0 <6.0.0
Enter fullscreen mode Exit fullscreen mode

So versions such as:

5.1.1
5.2.0
5.9.0
Enter fullscreen mode Exit fullscreen mode

may satisfy the range.

But:

6.0.0
Enter fullscreen mode Exit fullscreen mode

does not.


22. The ~ Operator

Consider:

~5.1.0
Enter fullscreen mode Exit fullscreen mode

This is generally more restrictive:

>=5.1.0 <5.2.0
Enter fullscreen mode Exit fullscreen mode

So:

5.1.1
5.1.9
Enter fullscreen mode Exit fullscreen mode

can match.

But:

5.2.0
Enter fullscreen mode Exit fullscreen mode

cannot.


23. Exact Versions

You can specify:

{
  "dependencies": {
    "some-package": "1.2.3"
  }
}
Enter fullscreen mode Exit fullscreen mode

This means the declared range is exactly:

1.2.3
Enter fullscreen mode Exit fullscreen mode

But remember:

The lockfile and package.json solve different problems.

For applications, the lockfile is normally what pins the complete dependency tree.


24. NPM Scripts

Consider:

{
  "scripts": {
    "dev": "node server.js",
    "test": "vitest",
    "build": "tsc",
    "lint": "eslint ."
  }
}
Enter fullscreen mode Exit fullscreen mode

Now:

npm run build
Enter fullscreen mode Exit fullscreen mode

executes:

tsc
Enter fullscreen mode Exit fullscreen mode

But NPM scripts have an important feature.

NPM automatically makes locally installed binaries available through the script environment.

If:

npm install --save-dev typescript
Enter fullscreen mode Exit fullscreen mode

installs:

node_modules/.bin/tsc
Enter fullscreen mode Exit fullscreen mode

you can write:

{
  "scripts": {
    "build": "tsc"
  }
}
Enter fullscreen mode Exit fullscreen mode

without:

./node_modules/.bin/tsc
Enter fullscreen mode Exit fullscreen mode

25. Why NPM Scripts Don't Need Global Tools

This is a powerful property.

Instead of:

npm install -g typescript
Enter fullscreen mode Exit fullscreen mode

your project can define:

{
  "devDependencies": {
    "typescript": "^5.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

Then:

npm run build
Enter fullscreen mode Exit fullscreen mode

uses the project's local TypeScript version.

This improves reproducibility.

You don't want:

Developer A
TypeScript 5.4

Developer B
TypeScript 5.7

CI
TypeScript 5.2
Enter fullscreen mode Exit fullscreen mode

You want:

Project
   |
   └── defined toolchain
Enter fullscreen mode Exit fullscreen mode

26. Lifecycle Scripts

NPM has lifecycle events.

For example:

preinstall
install
postinstall
Enter fullscreen mode Exit fullscreen mode

and:

prepublish
prepare
prepack
postpack
publish
postpublish
Enter fullscreen mode Exit fullscreen mode

This means NPM can execute scripts automatically during certain operations.

For example:

{
  "scripts": {
    "prepare": "npm run build"
  }
}
Enter fullscreen mode Exit fullscreen mode

This can be extremely useful for packages that need to build before being consumed.

But it also creates security considerations.


27. Why Install Scripts Are a Security Concern

Suppose you install:

npm install some-package
Enter fullscreen mode Exit fullscreen mode

and that package contains:

{
  "scripts": {
    "postinstall": "node malicious.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

Depending on installation configuration and package manager behavior, lifecycle scripts may execute automatically.

That means installing a package can potentially execute code on your machine.

This is one reason dependency security matters.

A package is not simply:

some JavaScript files
Enter fullscreen mode Exit fullscreen mode

It can contain:

JavaScript
+
metadata
+
scripts
+
dependencies
+
native components
Enter fullscreen mode Exit fullscreen mode

28. Supply Chain Security

Modern JavaScript applications often have:

Your Application
    |
    +-- dependency A
    |      |
    |      +-- dependency C
    |      +-- dependency D
    |
    +-- dependency B
           |
           +-- dependency E
Enter fullscreen mode Exit fullscreen mode

You may directly trust:

A
B
Enter fullscreen mode Exit fullscreen mode

but your application indirectly depends on:

C
D
E
Enter fullscreen mode Exit fullscreen mode

This creates a software supply chain.

A vulnerability in a transitive dependency can affect your application even if you never installed that package directly.


29. Auditing Dependencies

NPM provides:

npm audit
Enter fullscreen mode Exit fullscreen mode

This checks your dependency tree against known vulnerability information.

You can also use:

npm audit fix
Enter fullscreen mode Exit fullscreen mode

when appropriate.

But blindly running:

npm audit fix --force
Enter fullscreen mode Exit fullscreen mode

is not a complete security strategy.

Security fixes can sometimes involve major version changes or behavioral changes.

You should understand what is changing.


30. Dependency Updates

Useful commands include:

npm outdated
Enter fullscreen mode Exit fullscreen mode

which helps identify packages where newer versions are available.

You can then decide whether to update.

The important principle is:

Update
    ↓
Understand changes
    ↓
Run tests
    ↓
Build
    ↓
Deploy
Enter fullscreen mode Exit fullscreen mode

not:

Update everything
    ↓
Hope
Enter fullscreen mode Exit fullscreen mode

31. Lockfile Integrity

Modern lockfiles contain integrity information.

Conceptually:

Package
   |
   v
Downloaded artifact
   |
   v
Integrity hash
Enter fullscreen mode Exit fullscreen mode

This allows the package manager to verify that the downloaded content matches the expected artifact.

A simplified conceptual representation:

package
  |
  +-- resolved URL
  |
  +-- integrity hash
Enter fullscreen mode Exit fullscreen mode

This helps protect against unexpected modification of package contents during installation.


32. NPM Cache

NPM doesn't necessarily download everything from scratch every time.

It maintains a local cache.

Conceptually:

npm install
     |
     v
Check cache
   /   \
 hit   miss
 |       |
 v       v
reuse   registry
         |
         v
       cache
Enter fullscreen mode Exit fullscreen mode

This improves installation performance.

You can inspect the cache using commands such as:

npm cache verify
Enter fullscreen mode Exit fullscreen mode

33. Why node_modules Is So Large

A common joke in JavaScript:

"I installed three packages and got 900 MB."

The reason is the dependency graph.

You install:

A
Enter fullscreen mode Exit fullscreen mode

but A requires:

B
C
D
Enter fullscreen mode Exit fullscreen mode

and:

B -> E
C -> F
D -> G
Enter fullscreen mode Exit fullscreen mode

The tree grows quickly.

Modern NPM performs dependency tree optimization and deduplication where possible.


34. Dependency Deduplication

Suppose:

A -> lodash ^4.17.0

B -> lodash ^4.17.0
Enter fullscreen mode Exit fullscreen mode

There is no reason to necessarily install two copies.

NPM can potentially create:

node_modules/
└── lodash
Enter fullscreen mode Exit fullscreen mode

and both packages can resolve it.

This is called deduplication.

But if version requirements conflict:

A -> lodash 3.x

B -> lodash 4.x
Enter fullscreen mode Exit fullscreen mode

you may need:

node_modules/
├── lodash 4.x
└── A/
    └── node_modules/
        └── lodash 3.x
Enter fullscreen mode Exit fullscreen mode

35. Node.js Module Resolution

Why can:

import lodash from "lodash";
Enter fullscreen mode Exit fullscreen mode

work from:

src/services/user.js
Enter fullscreen mode Exit fullscreen mode

when lodash is located in:

node_modules/lodash
Enter fullscreen mode Exit fullscreen mode

Node.js uses module resolution rules.

Conceptually, it searches through relevant node_modules directories.

For a module imported from:

project/src/services/user.js
Enter fullscreen mode Exit fullscreen mode

Node can search locations conceptually like:

project/src/services/node_modules
project/src/node_modules
project/node_modules
node_modules
Enter fullscreen mode Exit fullscreen mode

until it finds a matching package.

This hierarchical structure is one of the reasons nested node_modules can work.


36. NPM Workspaces

Large projects often contain multiple packages.

For example:

company-project/
├── package.json
├── apps/
│   ├── web/
│   └── api/
└── packages/
    ├── ui/
    └── config/
Enter fullscreen mode Exit fullscreen mode

This is a monorepo.

NPM Workspaces allow these packages to be managed together.

Root:

{
  "private": true,
  "workspaces": [
    "apps/*",
    "packages/*"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Now NPM understands the repository as a collection of related packages.


37. Why Workspaces Matter

Imagine:

apps/web
Enter fullscreen mode Exit fullscreen mode

depends on:

packages/ui
Enter fullscreen mode Exit fullscreen mode

Instead of publishing ui every time you change it, the workspace can link the local package.

Conceptually:

apps/web
     |
     v
packages/ui
Enter fullscreen mode Exit fullscreen mode

This enables local package development.


38. Workspace Architecture

A realistic structure might be:

my-company/
│
├── package.json
├── package-lock.json
│
├── apps/
│   ├── frontend/
│   │   └── package.json
│   │
│   └── backend/
│       └── package.json
│
└── packages/
    ├── shared/
    │   └── package.json
    │
    ├── eslint-config/
    │   └── package.json
    │
    └── tsconfig/
        └── package.json
Enter fullscreen mode Exit fullscreen mode

This is a powerful structure for large applications.


39. Workspace Commands

You can target a workspace.

For example:

npm run build --workspace=frontend
Enter fullscreen mode Exit fullscreen mode

or:

npm install lodash --workspace=backend
Enter fullscreen mode Exit fullscreen mode

You can also run commands across workspaces.

This lets one root repository coordinate multiple projects.


40. Creating a Real Package

Let's build a small package.

Create:

mkdir string-tools
cd string-tools
npm init
Enter fullscreen mode Exit fullscreen mode

Or:

npm init -y
Enter fullscreen mode Exit fullscreen mode

You'll get:

{
  "name": "string-tools",
  "version": "1.0.0"
}
Enter fullscreen mode Exit fullscreen mode

Now create:

src/
└── index.js
Enter fullscreen mode Exit fullscreen mode

with:

export function capitalize(value) {
  if (!value) return value;

  return value.charAt(0).toUpperCase() + value.slice(1);
}
Enter fullscreen mode Exit fullscreen mode

41. Build Output

For a real package, you may want:

string-tools/
├── src/
│   └── index.js
├── dist/
│   └── index.js
├── package.json
└── README.md
Enter fullscreen mode Exit fullscreen mode

The consumer should ideally depend on:

dist/
Enter fullscreen mode Exit fullscreen mode

rather than your development source tree.

Your package metadata can define:

{
  "main": "./dist/index.js",
  "exports": {
    ".": "./dist/index.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

42. Package Versioning

Suppose your first release is:

1.0.0
Enter fullscreen mode Exit fullscreen mode

You fix a bug:

1.0.1
Enter fullscreen mode Exit fullscreen mode

You add backward-compatible functionality:

1.1.0
Enter fullscreen mode Exit fullscreen mode

You introduce a breaking API change:

2.0.0
Enter fullscreen mode Exit fullscreen mode

NPM can manage these version changes:

npm version patch
npm version minor
npm version major
Enter fullscreen mode Exit fullscreen mode

For example:

npm version patch
Enter fullscreen mode Exit fullscreen mode

can move:

1.0.0
Enter fullscreen mode Exit fullscreen mode

to:

1.0.1
Enter fullscreen mode Exit fullscreen mode

43. Publishing a Package

Before publishing:

npm login
Enter fullscreen mode Exit fullscreen mode

Then inspect:

npm pack --dry-run
Enter fullscreen mode Exit fullscreen mode

Run tests:

npm test
Enter fullscreen mode Exit fullscreen mode

Build:

npm run build
Enter fullscreen mode Exit fullscreen mode

Then:

npm publish
Enter fullscreen mode Exit fullscreen mode

Conceptually:

Source
   |
   v
Build
   |
   v
Test
   |
   v
npm pack
   |
   v
Inspect artifact
   |
   v
npm publish
   |
   v
Registry
Enter fullscreen mode Exit fullscreen mode

44. Scoped Packages

You can create:

@abanoub/string-tools
Enter fullscreen mode Exit fullscreen mode

instead of:

string-tools
Enter fullscreen mode Exit fullscreen mode

A scoped package is represented in package.json as:

{
  "name": "@abanoub/string-tools"
}
Enter fullscreen mode Exit fullscreen mode

Scoped packages are especially useful for organizations and package families.

For example:

@company/ui
@company/config
@company/logger
@company/utils
Enter fullscreen mode Exit fullscreen mode

45. Public vs Private Packages

A scoped package can be published publicly depending on its configuration and registry setup.

For private organizational packages, teams often use private registries.

The architecture becomes:

Developer
   |
   v
Private Registry
   |
   +-- @company/ui
   +-- @company/auth
   +-- @company/config
Enter fullscreen mode Exit fullscreen mode

This is common in enterprise environments.


46. Custom Registries

NPM doesn't have to communicate with only one registry.

You can configure registries.

For example, organizations can use internal registries for:

private packages
internal libraries
proprietary tooling
Enter fullscreen mode Exit fullscreen mode

This creates a model like:

Application
    |
    +----------+
    |          |
    v          v
Public       Private
Registry     Registry
Enter fullscreen mode Exit fullscreen mode

This is important in enterprise development.


47. Authentication

Publishing requires authentication.

The registry needs to know:

Who are you?
Enter fullscreen mode Exit fullscreen mode

and:

Are you allowed to publish this package?
Enter fullscreen mode Exit fullscreen mode

Authentication can involve:

  • login credentials
  • access tokens
  • organization permissions
  • two-factor authentication

Never put registry credentials directly into source code.

Especially never commit secrets such as:

.npmrc
Enter fullscreen mode Exit fullscreen mode

if it contains sensitive authentication tokens.


48. NPM Configuration

NPM behavior can be configured through configuration files and command-line options.

A common file is:

.npmrc
Enter fullscreen mode Exit fullscreen mode

You can have configuration at different scopes.

Conceptually:

Project
User
Global
Registry
Enter fullscreen mode Exit fullscreen mode

This is useful for:

registry configuration
authentication
proxy configuration
package settings
Enter fullscreen mode Exit fullscreen mode

But configuration containing secrets must be handled carefully.


49. Environment Variables in CI/CD

A safer CI pattern is:

CI Secret
   |
   v
Environment Variable
   |
   v
NPM Authentication
   |
   v
npm publish
Enter fullscreen mode Exit fullscreen mode

rather than committing:

NPM_TOKEN=...
Enter fullscreen mode Exit fullscreen mode

to Git.

For example, CI systems commonly provide secret storage mechanisms that expose tokens only during the workflow.


50. Package Naming Is Part of the API

Once a package is published:

my-package
Enter fullscreen mode Exit fullscreen mode

the name becomes part of its identity.

Changing the package name later effectively creates a different package.

Therefore package authors should think carefully about:

name
version
exports
API
README
license
Enter fullscreen mode Exit fullscreen mode

before publishing.


51. package.json as a Contract

A good way to think about package.json is:

It is a machine-readable contract describing your package.

It can define:

identity
version
dependencies
peer dependencies
scripts
entry points
exports
engines
files
license
repository metadata
Enter fullscreen mode Exit fullscreen mode

For example:

{
  "name": "string-tools",
  "version": "1.0.0",
  "type": "module",
  "main": "./dist/index.js",
  "exports": {
    ".": "./dist/index.js"
  },
  "files": [
    "dist"
  ],
  "scripts": {
    "build": "..."
  },
  "dependencies": {},
  "devDependencies": {}
}
Enter fullscreen mode Exit fullscreen mode

This metadata is as important as the code itself.


52. engines

A package can specify supported Node.js versions:

{
  "engines": {
    "node": ">=20"
  }
}
Enter fullscreen mode Exit fullscreen mode

This communicates:

This package expects Node.js 20 or newer.

This is particularly useful when your package depends on runtime features introduced in newer Node versions.


53. Performance: Where NPM Can Become Slow

Large repositories can experience slow installations because of:

Huge dependency graphs
Many packages
Network latency
Disk I/O
Extraction
Lifecycle scripts
Native modules
Cache misses
Enter fullscreen mode Exit fullscreen mode

A useful mental model is:

Install Time
    =
Network
+
Dependency Resolution
+
Disk I/O
+
Extraction
+
Scripts
+
Native Builds
Enter fullscreen mode Exit fullscreen mode

So not every slow installation is a network problem.


54. Why npm install Can Be Expensive

Imagine:

1000 packages
Enter fullscreen mode Exit fullscreen mode

Even if the total download size isn't enormous, NPM may still need to:

resolve metadata
download artifacts
verify integrity
extract files
create directories
create links
execute scripts
Enter fullscreen mode Exit fullscreen mode

On some systems, filesystem operations can become a major bottleneck.

node_modules contains a huge number of files.


55. Caching Improves Performance

CI environments can cache dependencies.

Conceptually:

First build
    |
    v
Download packages
    |
    v
Cache


Next build
    |
    v
Restore cache
    |
    v
Much less work
Enter fullscreen mode Exit fullscreen mode

However, cache invalidation matters.

A dependency cache should generally be associated with the dependency state, often using information derived from:

package-lock.json
Enter fullscreen mode Exit fullscreen mode

as part of the cache key.


56. Don't Commit node_modules

For almost all normal projects:

node_modules/
Enter fullscreen mode Exit fullscreen mode

should be in:

.gitignore
Enter fullscreen mode Exit fullscreen mode

You commit:

package.json
package-lock.json
Enter fullscreen mode Exit fullscreen mode

not:

node_modules/
Enter fullscreen mode Exit fullscreen mode

Why?

Because node_modules is:

large
generated
platform-dependent
reconstructible
Enter fullscreen mode Exit fullscreen mode

The source of truth is your dependency metadata and lockfile.


57. Cross-Platform Dependencies

Some packages contain native components.

For example:

package
   |
   +-- JavaScript
   |
   +-- native binary
Enter fullscreen mode Exit fullscreen mode

That native component may differ between:

Windows
Linux
macOS
Enter fullscreen mode Exit fullscreen mode

and architectures:

x64
ARM64
Enter fullscreen mode Exit fullscreen mode

This is another reason why committing node_modules is problematic.


58. Reproducible Builds

A strong Node.js project should aim for:

Developer Machine
       |
       v
CI
       |
       v
Production
Enter fullscreen mode Exit fullscreen mode

to use essentially the same dependency graph.

A common foundation is:

package.json
+
package-lock.json
+
fixed Node.js version
+
npm ci
Enter fullscreen mode Exit fullscreen mode

You can further enforce runtime versions using tools such as:

.nvmrc
Enter fullscreen mode Exit fullscreen mode

or:

"engines": {
  "node": ">=20"
}
Enter fullscreen mode Exit fullscreen mode

59. Dependency Management Strategy

A mature project shouldn't think:

"What is the newest version?"

Instead ask:

Do we need the update?
        |
        v
What changed?
        |
        v
Is it compatible?
        |
        v
Are there security implications?
        |
        v
Do tests pass?
        |
        v
Can we deploy safely?
Enter fullscreen mode Exit fullscreen mode

Dependency management is engineering, not button clicking.


60. Creating a Production-Quality Package

Let's define a realistic package:

logger-kit/
│
├── src/
│   └── index.ts
│
├── dist/
│   ├── index.js
│   └── index.d.ts
│
├── test/
│   └── logger.test.ts
│
├── package.json
├── package-lock.json
├── README.md
├── LICENSE
└── .gitignore
Enter fullscreen mode Exit fullscreen mode

A possible package.json:

{
  "name": "@company/logger-kit",
  "version": "1.0.0",
  "type": "module",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js"
    }
  },
  "files": [
    "dist",
    "README.md",
    "LICENSE"
  ],
  "scripts": {
    "build": "tsc",
    "test": "vitest run",
    "prepublishOnly": "npm run build && npm test"
  }
}
Enter fullscreen mode Exit fullscreen mode

Now publishing becomes safer:

npm publish
     |
     v
prepublishOnly
     |
     +--> build
     |
     +--> test
     |
     v
publish
Enter fullscreen mode Exit fullscreen mode

61. Why prepublishOnly Is Useful

Suppose you forgot to build:

src/
Enter fullscreen mode Exit fullscreen mode

but your package exposes:

dist/
Enter fullscreen mode Exit fullscreen mode

You could accidentally publish stale code.

Using:

{
  "scripts": {
    "prepublishOnly": "npm run build && npm test"
  }
}
Enter fullscreen mode Exit fullscreen mode

creates a publishing gate.

Now:

npm publish
Enter fullscreen mode Exit fullscreen mode

first runs:

build
+
test
Enter fullscreen mode Exit fullscreen mode

If either fails:

Publishing stops
Enter fullscreen mode Exit fullscreen mode

This is much safer.


62. Testing the Package Before Publishing

You can test the package artifact itself.

A powerful workflow is:

npm pack
Enter fullscreen mode Exit fullscreen mode

Then install the generated .tgz into a test project:

npm install ../logger-kit/logger-kit-1.0.0.tgz
Enter fullscreen mode Exit fullscreen mode

Now you are testing what consumers will actually receive.

This catches mistakes such as:

missing dist/
missing README
incorrect exports
missing type declarations
unexpected files
Enter fullscreen mode Exit fullscreen mode

63. A Real Package Release Pipeline

A mature package pipeline might look like:

Code Change
    |
    v
Tests
    |
    v
Lint
    |
    v
Build
    |
    v
npm pack
    |
    v
Inspect artifact
    |
    v
Version
    |
    v
Git Tag
    |
    v
Publish
    |
    v
Registry
Enter fullscreen mode Exit fullscreen mode

This is very different from:

npm publish
Enter fullscreen mode Exit fullscreen mode

and hoping everything works.


64. Versioning and API Compatibility

Imagine version:

1.4.0
Enter fullscreen mode Exit fullscreen mode

You have:

export function calculatePrice() {}
Enter fullscreen mode Exit fullscreen mode

Now you rename it:

export function calculateTotal() {}
Enter fullscreen mode Exit fullscreen mode

Existing consumers may break:

import { calculatePrice } from "my-package";
Enter fullscreen mode Exit fullscreen mode

This is a breaking API change.

Therefore:

1.x
Enter fullscreen mode Exit fullscreen mode

to:

2.0.0
Enter fullscreen mode Exit fullscreen mode

may be appropriate under SemVer.

Version numbers communicate compatibility expectations.


65. Deprecating APIs

Sometimes you don't want to immediately remove an API.

You can instead:

1.x
Enter fullscreen mode Exit fullscreen mode

keep:

calculatePrice()
Enter fullscreen mode Exit fullscreen mode

and introduce:

calculateTotal()
Enter fullscreen mode Exit fullscreen mode

Then document:

calculatePrice()
deprecated
Enter fullscreen mode Exit fullscreen mode

Later:

2.0.0
Enter fullscreen mode Exit fullscreen mode

can remove it.

This creates a migration path for consumers.


66. The Difference Between Package Manager and Build Tool

NPM is not primarily a build tool.

NPM manages:

packages
dependencies
scripts
publishing
registry interaction
Enter fullscreen mode Exit fullscreen mode

Your build may be performed by:

TypeScript
Vite
Webpack
Rollup
esbuild
tsup
Babel
Enter fullscreen mode Exit fullscreen mode

NPM can orchestrate these through scripts:

{
  "scripts": {
    "build": "vite build"
  }
}
Enter fullscreen mode Exit fullscreen mode

So:

NPM
  |
  +-- orchestrates
        |
        +-- TypeScript
        +-- Vite
        +-- ESLint
        +-- Tests
Enter fullscreen mode Exit fullscreen mode

67. NPM Is an Automation Layer

This is an important mental model.

A package.json can become a project command center:

{
  "scripts": {
    "dev": "...",
    "build": "...",
    "test": "...",
    "lint": "...",
    "format": "...",
    "prepare": "...",
    "release": "..."
  }
}
Enter fullscreen mode Exit fullscreen mode

Then developers only need:

npm run dev
npm run build
npm test
Enter fullscreen mode Exit fullscreen mode

This standardizes project operations.


68. Security: The Developer's Checklist

Before installing a package, consider:

Who maintains it?
How popular is it?
Is it actively maintained?
Does it have known vulnerabilities?
What dependencies does it bring?
Does it execute install scripts?
Does it request unusual permissions?
Is the package name correct?
Enter fullscreen mode Exit fullscreen mode

Package-name typos can be dangerous.

For example:

popular-package
Enter fullscreen mode Exit fullscreen mode

vs:

popluar-package
Enter fullscreen mode Exit fullscreen mode

A malicious package can attempt to exploit developer mistakes.

This is one aspect of dependency confusion / typosquatting risks.


69. Don't Automatically Trust Popular Packages

Popularity is useful information, but it isn't a complete security guarantee.

A package can become compromised through:

account takeover
malicious release
dependency compromise
maintainer compromise
build pipeline compromise
Enter fullscreen mode Exit fullscreen mode

Therefore security should consider the entire supply chain.


70. The Full NPM Mental Model

At this point, we can construct a much better mental model.

When you run:

npm install
Enter fullscreen mode Exit fullscreen mode

think:

                 package.json
                      |
                      v
               Dependency Ranges
                      |
                      v
              Dependency Resolver
                      |
                      v
                 Lockfile
                      |
                      v
               Package Metadata
                      |
                      v
                   Registry
                      |
                      v
                  Tarballs
                      |
                      v
               Integrity Check
                      |
                      v
              Local NPM Cache
                      |
                      v
                node_modules
                      |
                      v
               Lifecycle Scripts
Enter fullscreen mode Exit fullscreen mode

That is much closer to what NPM actually represents.


71. The Full Publishing Mental Model

And:

npm publish
Enter fullscreen mode Exit fullscreen mode

should be mentally understood as:

Source Code
     |
     v
Build
     |
     v
Tests
     |
     v
Package Metadata
     |
     v
File Selection
     |
     v
Tarball
     |
     v
Authentication
     |
     v
Registry
     |
     v
Versioned Package
Enter fullscreen mode Exit fullscreen mode

The package artifact then becomes something other developers can consume.


72. Application vs Library

There is an important difference between developing an application and developing a package.

Application

You control:

the entire deployment
Enter fullscreen mode Exit fullscreen mode

You typically care about:

package-lock.json
reproducibility
CI
security
runtime
Enter fullscreen mode Exit fullscreen mode

Library

Other people control:

their application
their Node version
their package manager
their dependencies
Enter fullscreen mode Exit fullscreen mode

Therefore libraries must care deeply about:

API compatibility
exports
peerDependencies
SemVer
types
runtime support
package size
published files
Enter fullscreen mode Exit fullscreen mode

73. NPM in a Monorepo

A mature monorepo might look like:

company/
│
├── package.json
├── package-lock.json
│
├── apps/
│   ├── web/
│   └── api/
│
└── packages/
    ├── ui/
    ├── database/
    ├── auth/
    └── config/
Enter fullscreen mode Exit fullscreen mode

The relationship can become:

             company/
                 |
       +---------+---------+
       |                   |
      apps              packages
       |                   |
   +---+---+         +-----+-----+
   |       |         |     |     |
  web     api       ui    auth   db
Enter fullscreen mode Exit fullscreen mode

Workspaces allow NPM to understand and coordinate this structure.


74. What NPM Doesn't Solve

NPM is powerful, but it doesn't solve everything.

It doesn't automatically guarantee:

secure dependencies
correct architecture
good package quality
backward compatibility
fast builds
safe releases
Enter fullscreen mode Exit fullscreen mode

You still need engineering practices.

For example:

NPM
+
Git
+
CI/CD
+
Tests
+
Security scanning
+
Code review
+
Versioning strategy
Enter fullscreen mode Exit fullscreen mode

together form a production-grade ecosystem.


75. Practical Production Checklist

Before deploying a Node.js application:

[ ] package.json is correct
[ ] package-lock.json is committed
[ ] node_modules is ignored
[ ] npm ci is used in CI
[ ] Node.js version is controlled
[ ] dependencies are reviewed
[ ] npm audit is checked
[ ] secrets aren't committed
[ ] lifecycle scripts are understood
[ ] production dependencies are separated
[ ] build is reproducible
[ ] tests pass
Enter fullscreen mode Exit fullscreen mode

For a package:

[ ] package name is correct
[ ] version follows SemVer
[ ] exports are correct
[ ] types are included
[ ] files are intentionally selected
[ ] README exists
[ ] LICENSE exists
[ ] tests pass
[ ] package artifact is inspected
[ ] authentication is secure
[ ] publishing is automated carefully
Enter fullscreen mode Exit fullscreen mode

76. The Most Important Concept

The biggest mistake is thinking:

NPM is just a command that downloads packages.

A better mental model is:

NPM is an ecosystem for resolving, installing, executing, managing, and publishing versioned software packages.

It connects:

Developers
    |
    v
package.json
    |
    v
Dependency Graph
    |
    v
Resolver
    |
    v
Lockfile
    |
    v
Registry
    |
    v
Package Artifact
    |
    v
node_modules
    |
    v
Application
Enter fullscreen mode Exit fullscreen mode

And for package authors:

Source Code
    |
    v
Build
    |
    v
Package Artifact
    |
    v
Registry
    |
    v
Other Developers
Enter fullscreen mode Exit fullscreen mode

Once you understand this model, many NPM behaviors stop being mysterious.

Why does package-lock.json exist?

Because dependency resolution needs reproducibility.

Why shouldn't we commit node_modules?

Because it is generated installation state.

Why do peer dependencies exist?

Because libraries often need to integrate with a dependency already owned by the consuming application.

Why does npm ci exist?

Because CI needs deterministic, clean installations.

Why do workspaces exist?

Because large repositories contain multiple related packages.

Why does SemVer matter?

Because dependency compatibility needs a shared versioning language.

Why can installing a package be a security risk?

Because packages are executable software, not just static files.

Why should package authors inspect npm pack --dry-run?

Because the published artifact—not your Git repository—is what consumers actually receive.


Conclusion

If you only memorize:

npm install
npm run
npm publish
Enter fullscreen mode Exit fullscreen mode

you know how to use NPM.

If you understand:

dependency graphs
resolution
SemVer
lockfiles
node_modules
caching
scripts
lifecycle hooks
registries
package artifacts
exports
peer dependencies
workspaces
publishing
security
reproducible builds
Enter fullscreen mode Exit fullscreen mode

you understand how the NPM ecosystem actually works.

And that's a completely different level of knowledge.

The goal isn't to memorize more NPM commands.

The goal is to understand the system behind those commands.

Once you do, debugging dependency conflicts, designing packages, optimizing installations, securing dependencies, building monorepos, and publishing production-quality libraries become much easier to reason about.

Top comments (0)