How to fix npm ERR! pre-install script failed (pre/post script execution error) in Node.js

Node.jsINTERMEDIATEHIGHUpdated Dec 9, 2025· 288 views

This error occurs when npm lifecycle scripts (preinstall, postinstall, prepublish, etc.) fail during package installation. These scripts are defined in package.json and run at specific stages of the installation process. Failures typically stem from missing build tools, permission issues, or incompatible dependencies.

Quick fix

Fixes npm ERR! pre-install script failed (pre/post script execution error)

npm install --verbose
# or for maximum detail
npm install --loglevel silly
  1. Identify which package and script is failing
  2. Install required build tools
  3. Check Node.js version compatibility
  4. Fix permission issues
node.js — error
npm install --verbose
# or for maximum detail
npm install --loglevel silly
npm ERR! pre-install script failed (pre/post script execution error)

What this error means

npm lifecycle scripts are custom commands that run automatically at specific points during package installation, publishing, or other npm operations. The most common are "preinstall" (runs before installation), "postinstall" (runs after installation), and "prepare" (runs before packaging). When npm encounters "pre-install script failed" or "post-install script failed", it means a script defined in package.json's "scripts" field returned a non-zero exit code, indicating failure. This halts the installation process to prevent incomplete or corrupted package setup. These scripts are often used for compiling native dependencies (node-gyp), downloading additional assets, setting up configuration files, or verifying system requirements. When they fail, it's usually because required build tools are missing, permissions are insufficient, or dependencies have platform-specific requirements that aren't met on your system.

Typical symptoms

  • npm install command exits with error code during package installation
  • Error message shows "npm ERR!" followed by "preinstall" or "postinstall" script failure
  • Specific package name appears in error output with lifecycle script details
  • Installation process stops partway through with "code 1" or other non-zero exit code
  • Native module compilation fails with "node-gyp" or "make" errors
  • CI/CD pipeline fails during npm install step
  • Different behavior between local development and production environments
  • Error references missing Python, compiler, or build tools

Common causes

  1. Missing system build tools required for native module compilation (Python, C++ compiler, make)
  2. Insufficient file system permissions to execute scripts or write compiled output
  3. Package depends on platform-specific binaries not available on current OS
  4. Node.js version incompatibility with native dependencies
  5. Network failures during postinstall asset downloads
  6. Script syntax errors or missing dependencies in custom lifecycle scripts
  7. Environment variables or configuration required by script not set
  8. Package maintainer script assumes specific directory structure or tools
  9. Outdated npm or Node.js version incompatible with modern package requirements

How to fix "npm ERR! pre-install script failed (pre/post script execution error)"

1Identify which package and script is failing

Run npm install with verbose logging to see detailed error output:

bash
npm install --verbose
# or for maximum detail
npm install --loglevel silly

Look for the specific package name and script type (preinstall/postinstall) in the error output:

bash
npm ERR! <package-name>@1.0.0 postinstall: node-gyp rebuild
npm ERR! Exit status 1

Once you know the failing package, you can target the fix more effectively. Check the package's documentation for known installation issues or system requirements.

2Install required build tools

Many lifecycle script failures occur because native dependencies require compilation tools:

Ubuntu/Debian:

bash
sudo apt-get update
sudo apt-get install -y build-essential python3

macOS:

bash
xcode-select --install

Windows:

powershell
# Install Visual Studio Build Tools
npm install --global windows-build-tools

# Or install directly from Microsoft:
# https://visualstudio.microsoft.com/downloads/
# Select "Desktop development with C++"

For all platforms, ensure Python is available:

bash
python --version  # Should be Python 3.x
# or
python3 --version

# Set Python path for node-gyp if needed
npm config set python /usr/bin/python3

After installing build tools, clear npm cache and retry:

bash
npm cache clean --force
rm -rf node_modules package-lock.json
npm install
3Check Node.js version compatibility

Ensure your Node.js version is compatible with the package requirements:

bash
node --version
npm --version

Check the failing package's package.json for engine requirements:

bash
# View package details
npm view <package-name> engines

# Example output:
# { node: '>=14.0.0', npm: '>=6.0.0' }

If your version is incompatible, use nvm (Node Version Manager) to switch:

bash
# Install nvm if not already installed
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# Install and use compatible Node version
nvm install 18
nvm use 18

# Verify and reinstall
node --version
npm install

For projects with .nvmrc file:

bash
nvm use
npm install
4Fix permission issues

If the error mentions EACCES or permission denied, fix npm permissions:

Option 1 - Use a Node version manager (recommended):

bash
# This avoids permission issues entirely
# Install nvm or fnm instead of system Node
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

Option 2 - Fix npm global directory permissions:

bash
# Create a directory for global packages
mkdir ~/.npm-global

# Configure npm to use it
npm config set prefix '~/.npm-global'

# Add to PATH (add this to ~/.bashrc or ~/.zshrc)
export PATH=~/.npm-global/bin:$PATH

# Reload shell configuration
source ~/.bashrc  # or source ~/.zshrc

Option 3 - Change node_modules ownership (use cautiously):

bash
# Only if you own the project directory
sudo chown -R $(whoami) node_modules
npm install

Never use sudo with npm install unless absolutely necessary, as it can create permission problems and security risks.

5Skip lifecycle scripts temporarily for diagnosis

Bypass scripts to identify if the issue is script-specific or dependency-related:

bash
# Install without running lifecycle scripts
npm install --ignore-scripts

# Verify the application still works
npm start

If the application works without scripts, the failing script may be optional (e.g., optional optimizations). You can selectively rebuild specific packages:

bash
# Rebuild a specific package
npm rebuild <package-name>

Warning: Some packages require postinstall scripts for essential functionality. Only use --ignore-scripts for diagnosis, not production deployments.

For CI/CD environments where scripts are problematic but needed:

bash
# Install without scripts, then rebuild trusted packages
npm ci --ignore-scripts
npm rebuild <trusted-package-1> <trusted-package-2>
6Update npm and clear caches

Outdated npm versions can cause lifecycle script failures:

bash
# Update npm to latest version
npm install -g npm@latest

# Verify update
npm --version

# Clear all caches
npm cache clean --force

# Remove existing installations
rm -rf node_modules package-lock.json

# Fresh install
npm install

If issues persist, check for corrupted npm cache:

bash
# Verify cache integrity
npm cache verify

# Output shows cache status and any corruption

For stubborn cases, reset npm configuration:

bash
# Show current config
npm config list

# Reset to defaults (backs up old config)
npm config edit
# Or delete specific problematic settings
npm config delete <key>
7Check package-specific documentation and alternatives

Research the specific failing package for known issues:

bash
# Check package README and issues on GitHub
npm repo <package-name>  # Opens GitHub repo

# Search for existing issues
# Look for terms like "installation", "postinstall", "node-gyp"

Common problematic packages and solutions:

node-sass (deprecated):

bash
# Replace with dart-sass
npm uninstall node-sass
npm install sass

bcrypt (native dependency):

bash
# Use pure JavaScript alternative
npm install bcryptjs

sharp (image processing):

bash
# Ensure required libraries are installed
# Ubuntu/Debian:
sudo apt-get install libvips-dev

sqlite3, better-sqlite3:

bash
# Use prebuilt binaries
npm install --build-from-source=false
# Or specify target platform
npm install --target_platform=linux --target_arch=x64

Always check if a pure JavaScript alternative exists that avoids native compilation.

Advanced notes

Understanding npm Lifecycle Script Order

npm executes scripts in a specific order during installation:

1. preinstall
2. install (deprecated, use preinstall/postinstall)
3. postinstall
4. prepublish (deprecated)
5. preprepare
6. prepare
7. postprepare

Understanding this order helps debug which stage is failing. Use npm run <script> to manually execute scripts for testing.

Custom Scripts and Debugging

If you maintain a package with lifecycle scripts, make them robust:

javascript
// postinstall.js - Example with proper error handling
try {
  const os = require('os');
  const platform = os.platform();

  // Check platform before running platform-specific commands
  if (platform === 'win32') {
    console.log('Windows detected, skipping optional compilation');
    process.exit(0);  // Success
  }

  // Your script logic here
  require('child_process').execSync('make build', {
    stdio: 'inherit'
  });

} catch (error) {
  console.warn('Optional build failed:', error.message);
  console.warn('Package will work with reduced functionality');
  process.exit(0);  // Don't fail installation for optional features
}

Docker and CI-Specific Considerations

In Dockerfile, install build tools in the same layer as npm install:

dockerfile
FROM node:18

# Install build dependencies
RUN apt-get update && apt-get install -y \
    python3 \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

# Copy package files
COPY package*.json ./

# Install with build from source
RUN npm ci --build-from-source

# Copy application code
COPY . .

Multi-stage Docker builds to avoid including build tools in final image:

dockerfile
# Build stage
FROM node:18 as builder
RUN apt-get update && apt-get install -y build-essential python3
COPY package*.json ./
RUN npm ci --build-from-source
COPY . .

# Production stage
FROM node:18-slim
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app .
CMD ["node", "server.js"]

GitHub Actions Example

yaml
name: CI
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'

      # Install build tools
      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y build-essential python3

      - name: Install packages
        run: npm ci

      - name: Run tests
        run: npm test

Prebuilt Binaries

Many native packages offer prebuilt binaries to avoid compilation:

json
// package.json
{
  "scripts": {
    "install": "node-pre-gyp install --fallback-to-build"
  }
}

Check package documentation for:
- Binary releases on GitHub
- node-pre-gyp configuration
- Platform-specific install instructions

Package Security Considerations

Lifecycle scripts execute arbitrary code. Audit packages carefully:

bash
# Review scripts before installing
npm view <package-name> scripts

# Use npm audit
npm audit

# Check package reputation
npm view <package-name> maintainers

Consider using --ignore-scripts in CI for untrusted dependencies, then selectively rebuild known packages.

Workspaces and Monorepos

In monorepo setups with npm workspaces, script failures can cascade:

json
// root package.json
{
  "workspaces": [
    "packages/*"
  ],
  "scripts": {
    "postinstall": "npm run build --workspaces --if-present"
  }
}

Use --workspace flag to isolate failures:

bash
npm install --workspace=packages/app --ignore-scripts

Troubleshooting Environment Variables

Some scripts require specific environment variables:

bash
# Common environment variables for native builds
export PYTHON=/usr/bin/python3
export npm_config_build_from_source=true
export npm_config_target_arch=x64

# For Windows
set PYTHON=C:\Python39\python.exe

npm install

Alternative Package Managers

If npm continues to fail, try alternative package managers:

bash
# Yarn (handles lifecycle scripts differently)
yarn install

# pnpm (stricter dependency resolution)
pnpm install

These may succeed where npm fails due to different script execution contexts.

Frequently asked questions

What does "npm ERR! pre-install script failed (pre/post script execution error)" mean?
npm lifecycle scripts are custom commands that run automatically at specific points during package installation, publishing, or other npm operations. The most common are "preinstall" (runs before installation), "postinstall" (runs after installation), and "prepare" (runs before packaging). json's "scripts" field returned a non-zero exit code, indicating failure.
How do I fix "npm ERR! pre-install script failed (pre/post script execution error)"?
This error occurs when npm lifecycle scripts (preinstall, postinstall, prepublish, etc.) fail during package installation. These scripts are defined in package.json and run at specific stages of the installation process. Failures typically stem from missing build tools, permission issues, or incompatible dependencies.
What causes "npm ERR! pre-install script failed (pre/post script execution error)"?
Missing system build tools required for native module compilation (Python, C++ compiler, make) Insufficient file system permissions to execute scripts or write compiled output Package depends on platform-specific binaries not available on current OS
Is the "npm ERR! pre-install script failed (pre/post script execution error)" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading