How to fix npm throwing error without sudo?

Better Stack Team
Updated on March 11, 2024

If you are encountering errors when trying to run npm without using sudo, it's likely related to permission issues. Running npm with sudo can lead to problems with file ownership and permissions, and it's generally not recommended.

Here are a few steps you can take to fix npm permission errors without using sudo:

Change npm's Default Directory

Change npm's default directory to a directory you own:

 
# Create a directory for global installations in your home folder
mkdir ~/.npm-global

# Configure npm to use the new directory
npm config set prefix '~/.npm-global'

# Add the following line to your profile or rc file (e.g., ~/.bashrc, ~/.zshrc)
export PATH=~/.npm-global/bin:$PATH

# Restart your terminal or run `source ~/.bashrc` (or the appropriate rc file)

Fix npm Global Package Installation

If you have installed global packages using sudo, you might need to change ownership of the related directories. Replace username with your actual username.

 
sudo chown -R $(whoami) ~/.npm-global
sudo chown -R $(whoami) /usr/local/lib/node_modules

Uninstall Global Packages Installed with sudo

Remove global packages installed with sudo:

 
sudo npm ls -g --depth=0 | awk -F/ '/node_modules/ && !/\\/npm$/ {print $NF}' | xargs sudo npm -g rm

Reinstall npm Packages Locally

If you're having issues with a specific project, navigate to the project directory and reinstall the npm packages:

 
rm -rf node_modules
npm install

Use a Node Version Manager (NVM)

Consider using NVM to manage your Node.js versions. NVM allows you to install Node.js versions without requiring elevated privileges and helps avoid permission issues.

Follow the instructions on the NVM GitHub repository: https://github.com/nvm-sh/nvm

After performing these steps, you should be able to run npm without using sudo and resolve permission-related issues. Always be cautious when using sudo with npm, as it can lead to problems with file ownership and permissions.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github