The node-gyp rebuild error occurs when compiling native C++ modules fails. Install platform-specific build tools (Python, C++ compiler) to resolve this error.
Fixes npm ERR! command failed npm ERR! command sh -c node-gyp rebuild
xcode-select --installxcode-select --installnpm ERR! command failednpm ERR! command sh -c node-gyp rebuild
Node-gyp is a build tool that compiles native Node.js addons written in C/C++. This error occurs when node-gyp fails to compile a package's native code during npm install. The error typically indicates missing build tools—node-gyp requires Python and a C++ compiler to compile native modules. Different platforms need different tools: Visual Studio on Windows, Xcode on macOS, and build-essential on Linux.
Each platform needs specific tools:
macOS:
xcode-select --installUbuntu/Debian:
sudo apt-get update
sudo apt-get install build-essential python3Windows (run as Administrator):
npm install -g windows-build-toolsOr install Visual Studio 2022 with "Desktop development with C++" workload.
Alpine Linux (Docker):
RUN apk add --no-cache python3 make g++Node-gyp requires Python 3.6+:
# Check Python version
python3 --version
# Set Python path for npm
npm config set python /usr/bin/python3
# Or use environment variable
export npm_config_python=/usr/bin/python3Windows users should ensure Python is in PATH.
Ensure you have the latest node-gyp:
# Update global node-gyp
npm install -g node-gyp@latest
# Verify version
node-gyp --versionClear cached builds and reinstall:
# Remove node_modules and lockfile
rm -rf node_modules package-lock.json
# Clear npm cache
npm cache clean --force
# Reinstall
npm installNative modules are compiled for specific Node versions:
# Use nvm to switch versions
nvm install 18
nvm use 18
# Reinstall after switching
rm -rf node_modules && npm installLTS versions generally have better native module support.
Avoid using sudo with npm:
# Create npm global directory
mkdir -p ~/.npm-global
# Configure npm to use it
npm config set prefix '~/.npm-global'
# Add to PATH
export PATH=~/.npm-global/bin:$PATHAdd the export line to ~/.bashrc or ~/.zshrc.
After macOS upgrades, Xcode may need reset:
sudo xcode-select --reset
sudo xcode-select --installCommon packages requiring node-gyp: bcrypt, sqlite3, canvas, sharp, node-sass (deprecated), serialport.
For production, consider pure JavaScript alternatives:
- bcrypt → bcryptjs
- node-sass → sass (Dart Sass)
- sqlite3 → better-sqlite3 or sql.js
On Apple Silicon Macs (M1/M2), ensure you're using the correct architecture Node.js binary. Rosetta can cause issues with native modules.
For Docker builds, always install build tools in the Dockerfile before npm install.