Switch Between Multiple Versions of Node with NVM and Homebrew

Zaid Al-Dabbagh Profile Photo
Zaid Al-Dabbagh
Switch between multiple versions of node with homebrew banner

If you’re working on multiple projects, and wish to quickly switch between different versions of Node due to compatibility, then Homebrew might come in handy.

Caution

[ 23 Jun 2023 Update | As recommended by @renzo.castillo ]

The instructions below assumes that you’re using the Bash Editor, if you’re unsure run echo $SHELL. For example if you’re using Zsh shell, then you’ll need to update your ~/.zshrc file instead of the noted ~/.bash_profile.

Approach 1 — Use of NVM

[ 29 Mar 2022 Update ]

I’d like to make a small update to this post, by also mentioning that there’s another approach to easily switch between different node versions, and that is to use Node Version Manager (NVM).

# Step 1 — Install NVM
# ====================
# Install NVM with homebrew
$ brew install nvm
# Create system directory for nvm
$ mkdir ~/.nvm
# Add the following to your ~/.bash_profile (or ~/.zshrc if you're using Zsh shell).
export NVM_DIR=~/.nvm
source $(brew --prefix nvm)/nvm.sh
# Read and execute your updated ~/.bash_profile
$ source ~/.bash_profile
# Verify nvm is installed
$ nvm --version
***
# Check all available remote versions
$ nvm ls-remote
# Install specific version
$ nvm install 16.14.2
# Check locally installed versions
$ nvm ls
# Use specific version
$ nvm use 16.14.2
***
# Set specific version to be default
nvm alias default 16
# Switch to default version on environment
$ nvm use default

Approach 2— Use of Homebrew (Mac Only)

# Install LATEST stable version of node
$ brew install node

# Install OLD version of node
$ brew install node@8

# Check version of installed node
$ node -v
v10.4.1
***
# Unlink LATEST version of node
$ brew unlink node

# Link OLD version of node
$ brew link node@8
***
# Update your ~/.bash_profile (or ~/.zshrc if you're using Zsh shell) to point to OLD version.
$ echo 'export PATH="/usr/local/opt/node@8/bin:$PATH"' >> ~/.bash_profile
# Read and execute your updated ~/.bash_profile
$ source ~/.bash_profile
***
# Open a new terminal window and verify version
$ node -v
v8.16.1

Disclaimer

It is worth mentioning too that if switching constantly between versions of Node and/or other tech, then you should consider use of environment management tools like Vagrant or Docker. Even with the benefits it provides, I have personally preferred the barebones environment setup on my work machine for better more responsive performance.

References

https://discourse.brew.sh/t/managing-brews-node-versions/2395