Search code examples
npmnpm-installsudo

Can I Install NPM Packages Using Sudo?


I was recently prompted to install a patch of NPM using npm install -g npm, though this process fails. Below are excerpts from the error message.

npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/npm
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/npm/node_modules

and

npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

Is it safe to install the patch using sudo? If not what is the proper fix for this issue?


Solution

  • Yes, you can do it, but no, it is not safe. Lots of people do it, but they shouldn't. If you install with sudo, then all the package's dependencies and subdependencies (which can be a very large number of packages) can run lifecycle scripts as root, basically doing anything they want. You can mitigate that with --ignore-scripts but then things you install might not work.

    The better solutions are in the npm docs about this topic: Install node and npm with a version manager (like nvm) or configure npm to do global installs in a directory where you will not need to use sudo.

    All that said, for your specific situation--just updating npm itself--using sudo is a very common solution despite being one that is not all that advisable. Installing npm with a version manager is a better idea if you are on a development machine (like your personal laptop).