npx
), it’s common to run into permission issues if they’re trying to be installed in system directories. The best way to avoid this problem and never use sudo
again with npm
or npx
is to configure npm to install global packages in a local directory.sudo
when running npm
or npx
.You need to create a new directory in your home folder for storing global npm packages. This will avoid using system directories.
mkdir ~/.npm-global
Now, set npm to use this newly created directory for global packages.
npm config set prefix '~/.npm-global'
The next step is to add this directory to your system's PATH
so your shell knows where to find the installed global packages.
If you're using bash:
echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
If you're using zsh (common on macOS or with Oh My Zsh):
echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
To check if everything is set up correctly, run the following command to verify the npx
version (or any global npm command).
npx --version
If it displays the version correctly without requiring sudo
, you're good to go!