Switch Between Node.js Versions with Homebrew

This is an abridged version of this wonderful article by Ralph J. Smit.

Installing the Latest Version of Node.js

Run brew install node. This installs the latest version of Node.js.

Installing Older Versions of Node.js

Run brew install node@16. This installs the latest version of Node.js 16. To install other major versions, replace 16 with a major version, like 17, 18 etc.

Switching between Node.js versions

To switch between Node.js versions, add an alias to the .zshrc file (or any other config file where aliases are kept). Add the following line for each version of Node.js you would like to use and replace node@16 with the correct major version.

alias node16="export PATH=/opt/homebrew/opt/node@16/bin:$PATH; node --version"
alias node18="export PATH=/opt/homebrew/opt/node@18/bin:$PATH; node --version"

Now the next time that you open up a new terminal, you can just type node16 to switch to Node.js 16 and node18 to switch to version 18.

Note that the switch only applies to one terminal session. Each time you open a new terminal window, you need to run this command again.

Setting a Default Version

So if you want to work on an older version, run one of the specified commands. At the end of the terminal session, the ‘environment’ is destroyed, and you’re always using the latest version of Node.js automatically.

If you want to change the default version of Node.js run

brew unlink node
brew link --overwrite node@16