Installing npm packages globally using root priviledges is a bad idea for a number of reasons. Some modern distributions will fail when trying to do so (e.g. Fedora). In this blog post I will explain the necessary steps to save npm packages to your user folder instead.

Create a folder for the packages

$ mkdir ~/.npm-packages

Configure npm to use a different path for globally installed packages

$ npm config set prefix ~/.npm-packages

Edit the configuration of your shell to make sure npm finds the binaries and man pages. For bash or zsh add the following to .bashrc or .zshrc:

# Add packages to path.
# Add manpages. Note that the unset command is NOT necessary if you modify it somewhere else.
unset MANPATH 
export MANPATH="$NPM_PACKAGES/share/man:$(manpath)"

In case you’re using the fish shell you need to edit .config/fish/

# Add packages to path.
set PATH "~/.npm-packages/bin" $PATH

You are now able to invoke

$ npm install -g gatsby-cli

without sudo!