Juanjo Salvador Juanjo Salvador - 10 months ago 48
Node.js Question

Run npm as superuser, it isn't a good idea?

I'm getting errors with

while trying to install/update packages without SU permissions on Linux.

The easy way to solve the problem is execute
sudo npm install <package>
, but I'm not sure if it is a good idea.

Best way is to become the owner of
folder, as I found into StackOverflow's questions and blog posts.

My question is: why run
as SU it isn't a good idea?

rsp rsp
Answer Source

Running npm as a super user has a risk of running some untrusted code as a super user which can potentially mess with your entire system. Running npm as an unprivileged user has a risk of running that code with less privileges and it won't be able to mess with the entire system - just with your own files (which can be equally bad, depending on how you look at it).

What I often do and recommend is to install Node in your home directory instead of globally on the system if it's your own computer. That way you don't have to run with sudo or su for npm or even for make install of Node itself.

I run a lot of versions of Node that I compile from sources sometimes with different switches and the convention that I use is to install Node in versioned directories, either globally in /opt (but then you need sudo) or locally in my home directory in ~/opt.

I do it like this:

wget https://nodejs.org/dist/v7.1.0/node-v7.1.0.tar.gz
tar xzvf node-v7.1.0.tar.gz
cd node-v7.1.0
./configure --prefix=$HOME/opt/node-v7.1.0
make && make test && make install

Then I create a symlink ~/opt/node pointing to ~/opt/node-v7.1.0 and I have:


in my .profile or .bashrc.

That way I don't have to run as super user for installing Node or for running npm.

As a bonus I can quickly switch my default Node version just by changing the symlink, and at any time I can run any other version if I change the PATH or run Node with a full path like ~/opt/node-v7.0.0/bin/node.

I explained that installation process in more detail in my other answers:

I don't want to go into too much detail here since this answer is about why running npm as a superuser is not a good idea - this installation process is just one solution to not have to run npm as a superuser.