Installing NPM Globals without Sudo

I recently purchased and set up my new iMac.

I might write something on the machine itself at some point and how it performs compared to my old MacBook Pro, but today I’m discussing NPM.

Before setup, I had come across an article from Andrew Crites, Don’t use sudo with npm.

In my MacBook, I think I handled most of my npm installations via sudo but wanted to make sure I wasn’t creating any hazards. As Andrew mentions, running npm install on a project has the potential to open your system up to malicious packages.

Following Andrew’s instruction, I added the following to my .npmrc file:

# ~/.npmrc tmp=/home/ajcrites/files/node-tmp
cache=/home/ajcrites/.npmcache prefix=/home/ajcrites/.npm

Obviously, subbing “ajcrites” for my own user name.

I, unfortunately, made the mistake of stopping there and not reading on, especially about ensuring binaries were on this new path.

This website was my first project on this new machine and I constantly ran into issues.

I could install services, like gatsby via npm install gatsby but I couldn’t run any commands like gatsby develop.

I found a quick workaround and instead used npx gatsby develop to spin up the development server. But when I added contentful, even npx wouldn’t work.

The errors I was receiving was zsh: command not found: gatsby and zsh: command not found: contentful.

I was on the search again.

Fortunately, after scouring the internet I found this issue on Stack Overflow.

The fix was quick and easy by adding export PATH=$PATH:/Users/username/.npm-global/bin to my .zshrc file.

Now I can run gatsby develop and import/export from contentful without issue.

I have two takeaways from this small hiccup. First, there are often better ways, especially if those ways require sudo. Secondly, read articles until the end.

Had I read further in Andrew Crites article, and I mean five short paragraphs further, I would have realized there was going to be another step.

Photo by Pankaj Patel on Unsplash.

Leave a Reply

%d bloggers like this: