Published on

Installing Global NPM Dependencies Without Using Sudo

Authors

I was setting up a new machine today and had to install some global npm dependencies ie:

npm install -g someTool

Generally, you have to use sudo to do this because of the location that npm tries to install these dependencies to. But using sudo to install global tools like this is a bad idea - it unnecessarily exposes your system to risk as it grants the installer full super user access over it during the install process.

I searched a little and found that npm has a configuration that lets you specify an alternate install location for global installs. This is, in fact, the same setting that yarn also uses by default, which is why yarn does not need sudo for yarn global adds. To do this run the following:

# create a directory for global installs (in your home directory so that you do not need special rights to access it)
mkdir ~/.npm-global
# configure npm to use the new directory
npm config set prefix '~/.npm-global'
# add the below to your .bashrc/.profile/.zshrc
echo "export PATH=~/.npm-global/bin:$PATH" >> ~/.zshrc

Restart your shell after which you should be able to run the following without sudo:

npm install -g someTool

You can read more about this over here.