.npmrc, scopes and private registries

npm · Practical · 12 min

Companies install from private registries, and CI needs credentials without leaking them.

npm reads configuration from several places, highest priority first: command-line flags, environment variables (npm_config_<key>), the project .npmrc (next to package.json), the user ~/.npmrc, the global $PREFIX/etc/npmrc, and built-in defaults. npm config list shows the merged result and where each value came from.

Scopes are namespaces like @acme/ui. Route a scope to a different registry:

@acme:registry=https://npm.pkg.github.com

Everything else still comes from the default registry.

Authentication is configured per registry host with //host/:_authToken=.... Never commit real tokens. Reference an environment variable instead, which npm expands at runtime: //npm.pkg.github.com/:_authToken=${NPM_TOKEN}. Then CI provides NPM_TOKEN as a secret. Logging in interactively (npm login --registry=...) writes tokens to the user .npmrc, not the project one.

Other useful project settings: engine-strict=true (fail on unsupported Node versions in engines), save-exact=true, min-release-age, and audit-level.

Registry mirrors and proxies (Verdaccio, Artifactory, Nexus, GitHub Packages, AWS CodeArtifact) cache public packages and host private ones. npm 12 errors on unknown .npmrc keys, so typos no longer pass silently.

Example

# .npmrc in the project root (committed: no secrets, only references)
@acme:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}
engine-strict=true
save-exact=true
min-release-age=3

# Inspect the effective configuration and its sources
npm config list
npm config get registry                 # https://registry.npmjs.org/
npm config get @acme:registry           # https://npm.pkg.github.com

# CI: provide the token as an environment secret
NODE_AUTH_TOKEN=$GITHUB_TOKEN npm ci

Remember

  • Config layers: CLI > env > project > user > global > defaults
  • Route scopes with @scope:registry=
  • Use ${ENV_VAR} in .npmrc instead of literal tokens
  • npm 12 rejects unknown config keys

Watch out for

  • Committing a .npmrc that contains a literal _authToken value.

Check yourself

  1. How should a committed project .npmrc provide a registry token?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.npmjs.com/cli/v11/configuring-npm/npmrc