nvm and Node.js Version Management: Best Practices
nvm (Node Version Manager) lets you install and switch between multiple Node.js versions.
Installation
# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# Add to shell profile (~/.bashrc, ~/.zshrc)
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && . "$NVM_DIR/bash_completion"
# Reload shell
source ~/.zshrc
Essential Commands
# List available LTS versions
nvm ls-remote --lts
# Install specific version
nvm install 20
nvm install 20.11.0
# Install latest LTS
nvm install --lts
# Use a version (current session)
nvm use 20
# Set default version
nvm alias default 20
# List installed versions
nvm ls
# Current version
nvm current
# Uninstall version
nvm uninstall 18
.nvmrc Files
# Create .nvmrc in project root
echo "20" > .nvmrc
# or
echo "lts/iron" > .nvmrc
# Use version from .nvmrc
nvm use # reads .nvmrc automatically
nvm install # installs version from .nvmrc
Auto-switch with Shell Integration
# Add to ~/.zshrc for auto-switching
autoload -U add-zsh-hook
load-nvmrc() {
local nvmrc_path
nvmrc_path="$(nvm_find_nvmrc)"
if [ -n "$nvmrc_path" ]; then
local nvmrc_node_version
nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")
if [ "$nvmrc_node_version" = "N/A" ]; then
nvm install
elif [ "$nvmrc_node_version" != "$(nvm version)" ]; then
nvm use
fi
elif [ -n "$(PWD=$OLDPWD nvm_find_nvmrc)" ] && [ "$(nvm version)" != "$(nvm version default)" ]; then
nvm use default
fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc
Migration Between Versions
# Reinstall global packages when switching versions
nvm install 20 --reinstall-packages-from=18
# List globally installed packages
npm list -g --depth=0
# Migrate manually
nvm use 18
npm list -g --depth=0 > /tmp/packages.txt
nvm use 20
cat /tmp/packages.txt | awk '{print $2}' | grep -v npm | xargs npm install -g
Alternative: Volta
# Volta - faster alternative to nvm
curl https://get.volta.sh | bash
# Install and pin Node version
volta install node@20
volta pin node@20 # saves to package.json
# Automatic per-project version switching
Using .nvmrc files ensures your entire team uses the same Node.js version.