Receiving 'command not found' message while trying to use npm with sudo

I’m encountering an issue when I use npm with sudo on my computer. It works well when I run npm commands normally, but I get an error stating that the command is not found when I try to use it with sudo.

For instance, when I run:

sudo npm install -g yarn

I receive this error message:

sudo: npm: command not found

Yet, npm operates normally without sudo:

npm --version

This displays the version number correctly. I checked the location of npm using:

which npm

It returns:

/usr/local/node/bin/npm

I also reviewed my sudoers file and noticed that the secure_path setting reads:

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

This path seems correct to me, but I am still experiencing the same problem. Has anyone dealt with a similar issue? How can I resolve the problem so npm works with sudo?

Had this exact issue last month on a fresh Ubuntu server. Your Node install is somewhere sudo can’t find it. Skip messing with sudoers - that’s risky. Try sudo env PATH=$PATH npm install -g yarn instead. This keeps your current PATH just for that command. Worked perfectly for me and won’t create security holes. You could also symlink it: sudo ln -s /usr/local/node/bin/npm /usr/local/bin/npm to put npm where sudo expects it. Both ways are way safer than editing sudoers and they’ll fix your problem.

This happens because sudo uses a restricted PATH that doesn’t include your Node.js directory. Your npm is at /usr/local/node/bin/npm, but sudo only looks in standard system directories, so it can’t find npm. I encountered this same issue when I installed Node.js from source instead of using a package manager. You have two main fixes: add /usr/local/node/bin to secure_path in your sudoers file, or use the full path with sudo commands as mentioned. Alternatively, consider using a Node version manager like nvm, which installs packages to user directories and eliminates the need for sudo with global installs, making it a safer option.

hey, had a similar prob! try adding /usr/local/node/bin to secure_path in sudoers, or just run it like this: sudo /usr/local/node/bin/npm install -g yarn. should work!