less than 1 minute read

Don’t Use sudo With npm

I have seen quite a few programmers install global packages on their machine with sudo npm. Generally, that isn’t a great idea. I was inspired by Andrew Crites’s article “Don’t Use sudo with npm …still” to post this quick guide on configuring npm prefixes.

Why shouldn’t you use sudo with npm? Go read Crites’s article!

Creating a npm Prefix

Set a prefix in your npm configuration using the npm config command.

npm config set prefix '~/.local/'

This modifies your ~/.npmrc to include the following line.

prefix=~/.local/

Updating $PATH

If you intend to run globally installed packages from the command line you must add the new prefix location to your $PATH. Replace ~/.zshrc with the appropriate configuration file for your shell e.g. ~/.bashrc.

mkdir -p ~/.local/bin
echo 'export PATH="$HOME/.local/bin/:$PATH"' >> ~/.zshrc

Installing Global Packages

You can now install global packages in the scope of your user without sudo!

npm i -g packagename