NPM and Node tips to make your dev machine (slightly) safer

NPM is used as a convenient cross-platform package manager for a lot of developer tools. For many tools, the defacto way to install is npm install -g $TOOL. But installing anything via npm allows it to run untrusted code on your machine. Here are a few tips to minimize the risk: 1. NEVER run npm as sudo/root Node’s official documentation recommends not installing global packages as sudo/root. If you have already installed node through nvm ignore this step. If you use a system installed node e.g using Ubuntu’s apt-get, read through this guide for Linux/Mac or npm-g-nosudo which is a shell script for Linux. If you are lazy (like me), here’s a summary from the linked guide: mkdir -p "${HOME}/.npm-packages" && npm config set prefix "${HOME}/.npm-packages" Add this to your .bashrc or .zshrc: NPM_PACKAGES="${HOME}/.npm-packages" export PATH="$PATH:$NPM_PACKAGES/bin" # Preserve MANPATH if you already defined it somewhere in your config. # Otherwise, fall back to `manpath` so we can inherit from `/etc/manpath`. export MANPATH="${MANPATH-$(manpath)}:$NPM_PACKAGES/share/man" 2. Install/Use node using nvm or asdf Node’s official documentation recommends installing node as an unprivileged user using a node version manager. ...

May 28 2020 · 4 min · Raunak