After installing npm, I wanted to install http-server, but I got an error saying:

error-img
the reason is that node_module directroy is in a protected directory.

Apple Support: System Integrity Protection

There are three ways to solve this problem:

  1. Use sudo to install (not recommended)
  2. Turn off SIP (not recommended)
  3. Manually change npm’s default directories (suggested)

Using sudo to install will override system files. If a package contains malicious code, using sudo grants the code full system control, leading to severe security vulnerabilities.

SIP (System Integrity Protection) was introduced in macOS 10.13, which protects the following directories from modification:

  • /System
  • /usr
  • /bin
  • /sbin
  • /var

There’s a solution to turn off SIP (Disabling and Enabling System Integrity Protection | Apple Developer Documentation), but this is not recommended.

The best approach is to set a custom default directory for npm:

1
mkdir ~/npm-global
1
npm config set prefix ~/npm-global

add the following scripts in your bash_profile or ~/.zshrc if you use zsh:

1
2
export N_PREFIX="$HOME/npm-global" #depends on your directory
export PATH=$N_PREFIX/bin:$PATH

to make it work,execute:

1
source ~/.bash_profile #bash user

or

1
source ~/.zshrc  #zsh user

That’s it.