DEV Community

Cover image for Install packages globally without sudo on Linux / MacOS
Hamza Makraz
Hamza Makraz

Posted on

Install packages globally without sudo on Linux / MacOS

Originally published at makraz.com.

npm -- Install packages globally without sudo on Linux / MacOS

By default npm installs packages locally in the folder nodes_modules within your projects.
But sometimes with need to install packages globally for command-line as example.
For Linux / MacOS users npm will ask you to run it with elevated privileges,
which mean use the command sudo to be able to install globally (sudo npm install -g <package>)
and this may create permission(s) issue(s) for many users.
However there is a way to install packages globally for a given user without sudo.

For that we will follow these steps:

1. Create a directory for global packages
mkdir "~/.npm_packages"
Enter fullscreen mode Exit fullscreen mode
2. Tell npm where to store globally installed packages
npm config set prefix "~/.npm_packages"
Enter fullscreen mode Exit fullscreen mode
3. Ensure npm will find installed binaries and man pages

Add the following to your .bashrc / .zshrc:

NPM_PACKAGES="~/.npm_packages"

export PATH="$PATH:$NPM_PACKAGES/bin"

# Preserve MANPATH if you already defined it somewhere in your config.
# Otherwise, fall back to `manpath` so we can inherit from `/etc/manpath`.
export MANPATH="${MANPATH-$(manpath)}:$NPM_PACKAGES/share/man"
Enter fullscreen mode Exit fullscreen mode

NOTE: If you are running macOS, the .bashrc file may not yet exist, and the terminal will be obtaining its environment parameters from another file, such as .profile or .bash_profile. These files also reside in the user's home folder. In this case, simply adding the following line to them will instruct Terminal to also load the .bashrc file:

source ~/.bashrc
Enter fullscreen mode Exit fullscreen mode

See also: npm's documentation on "Fixing npm permissions".

Top comments (0)