Why you shouldn’t use sudo with npm [update]

posted by Sven

Update: This issue (here on GitHub) has been fixed now. You’ll find the fix for global npm installs here, according to npm’s Isaac the bug “didn’t go out in the recent Node.js release, so you can also click the Big Green Button on http://nodejs.org and it should fix it for you”. Thanks for fixing it! <3

I’m sure most of us have been in a situation were simply running a command doesn’t get us very far:

# npm install -g hoodie-cli
npm install -g hoodiecli Permission denied

So what do we do, we get the hammer out and run things with the almighty sudo:

sudo npm install -g hoodie-cli

The problem here is, if you don’t have a ~/.npm (npm’s cache folder) and you sudo it, the cache folder will get root:root permissions. So the next non sudo install will fail with:

npm ERR! Error: EACCES

This happens because by default, sudo does not set $HOME (i.e. impersonates) to the target user (which is root by default).

A possible solution would be running sudo with the ‘-H’ flag. Here’s what

man sudo

has to say about it:

The -H (HOME) option option sets the HOME environment variable to the home directory of the target user (root by default) as specified by the password database. The default handling of the HOME environment variable depends on sudoers(5) settings. By default, sudo will not modify HOME (see set_home and always_set_home in sudoers(5)). (source)

So

sudo -H npm install -g hoodle-cli

turns out to be the fix for this issue.

Either that, or don’t ever use npm with sudo.