When you install npm packages globally using the -g flag, you might encounter this error:
npm error code EACCES
npm error syscall mkdir
npm error path /usr/lib/node_modules/lib
npm error errno -13
npm error Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/lib'
npm error The operation was rejected by your operating system.
npm error It is likely you do not have the permissions to access this file as the current user
EACCES errors indicate permission denied issues.
To resolve this issue, choose one of the following methods.
Method 1: Change npm’s default global directory (Recommended)
Configure npm to use a directory in your home folder where you have write permissions.
Create a folder for global installations
npm config set prefix '~/.npm-global'
Update your shell environment
Add the following line to ~/.bashrc:
export PATH=~/.npm-global/bin:$PATH
Method 2: Use a Node Version Manager
Tools like nvm (Node Version Manager) install Node.js and npm directly in your home directory, bypassing the /usr/lib permission issues automatically.
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
Export NVM environment variables
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
Install a version of Node
Method 3: Change global directory ownership
Change the ownership of the existing node_modules folder to your current user.
sudo chown -R $(whoami) /usr/lib/node_modules
This method modifies system-level directory ownership. Use it with caution, and prefer Method 1 or Method 2 for a safer long-term solution.