Getting 'command not found' error when using npm with sudo privileges

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 using:

which npm

This shows:

/usr/local/node/bin/npm

I also checked my system’s secure path configuration in the sudoers file and it looks like this:

Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

I need to install global packages but sudo isn’t recognizing npm. How can I fix this issue so npm works properly with sudo?

Skip sudo with npm entirely. I hit this same issue last year and switching to nvm fixed everything. When you install Node through nvm, it puts npm in your user directory with the right permissions. Then you can just run npm install -g yarn without sudo at all. Way safer too - no permission conflicts or security risks from running package managers as root. Takes 5 minutes to set up nvm and reinstall Node, but it’ll save you tons of headaches later.

Been there so many times. You’re manually managing Node installs and fighting permission conflicts - that’s your problem.

Skip the symlink patches and sudoers edits. Just automate the whole setup instead. I built a workflow that handles Node versions, package installs, and permissions automatically.

It detects your system, installs the right Node version, fixes permissions, and batch installs your globals. No more sudo fights or path fixes.

Switching projects? Setting up new environments? Everything just works. Handles npm, yarn, whatever tools you use - zero permission headaches.

I use this across multiple machines and these config issues are gone. Takes 2 minutes to set up, then you’re done forever.

Check out https://latenode.com to build your own automated setup.

hey! looks like npm’s not in secure_path. you can add /usr/local/node/bin to your sudoers, or just run sudo /usr/local/node/bin/npm install -g yarn. that should do the trick!

This happens because sudo uses secure_path, which doesn’t include your Node.js directory. I’ve hit this same issue tons of times with different Node installations. Just create a symlink in a directory that’s already in secure_path. Run sudo ln -s /usr/local/node/bin/npm /usr/local/bin/npm and probably sudo ln -s /usr/local/node/bin/node /usr/local/bin/node for node too. After that, sudo will find npm no problem. Way cleaner than messing with the sudoers file and works everywhere.