When you install global npm packages (like 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.

Why Use This Solution?

Steps:

1. Create a Directory for Global npm Packages

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

2. Configure npm to Use This Directory

Now, set npm to use this newly created directory for global packages.

npm config set prefix '~/.npm-global'

3. Update Your PATH

The next step is to add this directory to your system's PATH so your shell knows where to find the installed global packages.

4. Verify the Configuration

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!