Skip to content
Latchkey

npm pre/post Script Failing the Run - Fix Lifecycle Hook Errors in CI

npm automatically runs pre<name> before and post<name> after npm run <name>. If the pre/post hook exits non-zero, the whole run fails - sometimes confusingly, since the main command itself may be fine.

What this error means

npm run build (or test/start) fails, but the error is from a prebuild/postbuild hook, not the build itself. The main script may never even run because the pre hook failed first.

npm output
> app@1.0.0 prebuild
> node scripts/check-env.js

Error: missing required env var API_URL
npm error code 1
# "build" never ran because "prebuild" failed

Common causes

A pre hook failed before the main script

npm runs pre<name> first; if it exits non-zero (a failing check, a missing tool), the main script never runs and the whole command fails.

A post hook failed after a successful main script

A post<name> step (cleanup, notification, upload) that fails marks the run as failed even though the main command succeeded.

How to fix it

Identify which lifecycle step failed

Read the script-name banner npm prints to see if the failure is pre, main, or post.

Terminal
# run the main step alone to isolate it
npm run build --ignore-scripts   # skips pre/post around explicit runs
# or run the hook directly to debug it
npm run prebuild

Keep lifecycle hooks intentional

  1. Reserve pre/post hooks for steps that genuinely must gate the main command.
  2. Move optional/cleanup work into separate explicit scripts so it cannot fail the main run.
  3. Make hook failures actionable (clear error messages) so CI logs point at the cause.

How to prevent it

  • Use pre/post hooks only for genuinely gating steps.
  • Move optional work out of the lifecycle chain.
  • Make hook errors clear so CI failures are easy to trace.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →