I’m having trouble running npm commands with sudo access. When I try to execute:
sudo npm install -g yarn
I get this error message:
sudo: npm: command not found
The weird thing is that npm works perfectly fine when I run it without sudo. I can check where npm is located by running:
which npm
This returns:
/usr/local/node/bin/npm
When I check my node installation with:
whereis node
I get:
node: /usr/bin/node /usr/lib/node /usr/bin/X11/node /usr/local/node
I looked at my sudoers configuration and found this line:
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
This path setup seems correct to me. Why can’t sudo find npm even though it works in my regular user session? How do I fix this issue so I can install global packages?
This happens because sudo runs with its own environment and PATH - it doesn’t inherit your user’s setup. Even though npm works fine in your regular shell, sudo can’t find it. I’ve hit this same issue on CentOS boxes with manual Node installs. Instead of messing with system paths, just use the full path: sudo /usr/local/node/bin/npm install -g yarn or use the -E flag to keep your current PATH: sudo -E env "PATH=$PATH" npm install -g yarn. I’d go with the second option. It preserves your PATH during the sudo command and you don’t have to deal with symlinks or sudoers config changes. Works across different distros and Node setups too.
skip sudo with npm entirely. use nvm or n instead - they install everything to your user directory, so no root access needed. much cleaner than dealing with symlinks or path issues.
Your npm is installed in /usr/local/node/bin/npm but sudo’s secure_path doesn’t include that directory. Sudo can see /usr/local/bin but not /usr/local/node/bin where npm actually lives. I hit this same issue on my Ubuntu server last year. Just create a symbolic link from npm’s location to a directory sudo can find:
sudo ln -s /usr/local/node/bin/npm /usr/local/bin/npm
This makes a symlink sudo can see. You’ll probably need to do the same for npx. You could also modify secure_path in your sudoers file to include /usr/local/node/bin, but the symlink is safer since you’re not messing with system security settings. Once you create the symlink, sudo npm commands should work fine.