npm Install Scripts: Risks for Authors and Users

npm lets a package run arbitrary commands when it is installed, through the preinstall, install and postinstall lifecycle scripts. That is how some native modules compile themselves. It is also how a compromised or malicious package gets code execution on a developer laptop or CI runner before a single line of it is imported. If you author packages, the safest install script is the one you do not ship.

What an install script can do

Lifecycle scripts run with the permissions of the user doing the install. They can read environment variables (including any tokens in CI), read files in the home directory, make network requests and write anywhere the user can. They run for transitive dependencies too, so one script deep in the tree runs for everyone who installs anything that depends on it. Several well-publicised registry incidents have used exactly this route, which is why security guidance from bodies such as OpenSSF repeatedly singles it out.

How users limit them

As an author, assume a growing share of your users install with scripts disabled. If your package breaks without its postinstall, it breaks for them.

Ways to avoid needing one

Why packages use install scriptsAlternative
Compiling native code on installShip prebuilt binaries as per-platform packages listed in optionalDependencies, with os and cpu fields so only the matching one installs. Several widely used tools are distributed this way.
Downloading a binary from elsewhereSame per-platform package approach, which also keeps the binary on the registry and covered by its integrity checks.
Printing a thank-you or funding messageUse the funding field; npm fund shows it on request.
Generating code or configGenerate at build time before publishing, or lazily on first use.
Setting up git hooks for contributorsUse prepare, which runs for local installs of your own repository and is not triggered when consumers install the published package from the registry.

If you must ship one

  1. Keep it short, readable and in the published tarball, not fetched from the network.
  2. Make it idempotent and make it exit cleanly when it cannot do its job, with a message pointing to a manual step.
  3. Never read or transmit environment variables beyond what the build strictly needs.
  4. Document it in the README, including how to run the step manually under --ignore-scripts.
  5. Treat adding a new install script in a minor or patch release as a notable change and call it out in the changelog; many teams review new scripts in their dependency updates, and a surprise one looks like an attack.

Related reading: following security advisories, checking what your tarball contains, and how optional dependencies behave.

Related pages