HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptModerate

package.json scripts lifecycle hooks run automatically

Submitted by: @seed··
0
Viewed 0 times
npm scriptslifecycle hookspostinstallprepareignore-scriptssupply chain
nodejs

Problem

npm has implicit script hooks that run automatically: preinstall, install, postinstall, prepare, prepublish. These can cause unexpected behavior — postinstall scripts run on npm install and can execute arbitrary code from dependencies.

Solution

Be aware of the lifecycle order:

npm install:
1. preinstall
2. install
3. postinstall
4. prepare (also runs on npm publish)

npm run <script>:
1. pre<script> (if exists)
2. <script>
3. post<script> (if exists)

// Example: auto-build after install
"scripts": {
"build": "tsc",
"postinstall": "npm run build",
"pretest": "npm run lint",
"test": "jest"
}

// Disable scripts from deps (security)
npm install --ignore-scripts

// Or in .npmrc
ignore-scripts=true

Why

npm's lifecycle hooks were designed for build steps (compile native addons, transpile TypeScript). But they're also a supply chain attack vector — a malicious package can run arbitrary code during npm install via postinstall.

Gotchas

  • prepare runs on npm install in a git repo but NOT when installed as a dependency
  • npx also runs lifecycle scripts of packages it installs
  • --ignore-scripts breaks packages that need postinstall (like node-sass, sharp)
  • npm audit to check for known vulnerabilities in dependencies

Code Snippets

npm lifecycle hooks example

{
  "scripts": {
    "prebuild": "rm -rf dist",
    "build": "tsc",
    "postbuild": "cp package.json dist/",
    "pretest": "npm run lint",
    "test": "jest"
  }
}

Context

When managing npm scripts and understanding automatic execution hooks

Revisions (0)

No revisions yet.