Use a Node version manager, or set npm's prefix to a folder in your home directory and add its bin folder to your PATH. Either way, global installs write to a place your user owns, so you never need sudo and package scripts never run as root.
Why sudo is the wrong fix
When npm install -g fails with a permissions error (EACCES), the quick answer online is to prefix the command with sudo. That works, and it is a bad habit. Packages can run lifecycle scripts during install. With sudo, those scripts run as root, so a single bad package can change anything on the machine, not just your files.
The npm documentation lists two ways to avoid the problem. It calls a Node version manager the best way to avoid permissions issues, and notes you do not need to uninstall your current Node.js first. The second is to configure npm to use a different directory.
Option 1: a version manager
A version manager installs Node and npm under your home directory. Global packages then live there too, owned by you. Pick a manager your team already uses, install it from its own documentation, and install a Node version through it.
Benefits beyond permissions: you can switch Node versions per project, and removing a version removes its global packages with it.
Option 2: change npm's default directory
The documented approach, which does not apply to Windows, has four steps:
- Make a hidden folder in your home directory for global packages.
- Set npm's prefix to that folder with
npm config set prefix. - Add the folder's bin directory to your PATH in your shell profile.
- Reload your profile and test a global install without sudo.
Fixing a machine that already used sudo
If you installed globals with sudo in the past, some folders may now be root owned. Do not run a recursive ownership change on system directories. A cleaner path is to reinstall Node through a version manager, then reinstall the few global tools you actually use.
Keep the global list short
Every global package is code that runs with your rights and sits on your PATH. List them with npm ls -g --depth=0 and ask of each: do I still use this, and can I run it with npx for one off use instead? For what npx runs, see what does npx run and how to use it safely.
| Approach | Root involved | Per project Node versions | Cleanup |
|---|---|---|---|
| sudo npm install -g | Yes | No | Hard |
| Version manager | No | Yes | Remove the version |
| Custom prefix | No | No | Delete the folder |
Safeguard can scan a project's dependencies and produce an SBOM, and the CLI installs with a curl or PowerShell installer, so it does not need npm at all. A free scan is at gold.safeguard.sh/scan.
Quick check
Is it ever fine to use sudo with npm?
It is a last resort. Fix the directory ownership problem with a version manager or a custom prefix instead.
Does a custom prefix work on Windows?
The npm page describes that method as not applying to Windows. A version manager is the documented route there.
Sources
Last reviewed: 19 October 2026.