Auto switch Node.js version using NVM & ZSH hooks

I'm using Ghostty with ZSH + OhMyZsh as my terminal setup. In all my projects I add an .nvmrc file to pin the Node.js version in code. This allows me to use the same version in GitHub Actions and easily match the Node.js version used in the production Docker images.

Switching Node.js versions manually is as simple as running:

nvm install

However, it would be more convenient if this happened automatically when changing directories or opening a terminal in a specific project folder. This behavior can be achieved using ZSH hooks.

Add the following snippet to your .zshrc file:

# Auto-switch Node.js versions when .nvmrc is present
autoload -U add-zsh-hook

load_nvm_version() {
  if [[ -f .nvmrc ]]; then
    nvm use || nvm install
  fi
}

add-zsh-hook chpwd load_nvm_version
load_nvm_version

With this setup, your Node.js environment will always match the expected version without manual intervention. Bonus: this should work in the built-in terminal of your editor of choice as well.

Update 12/02/2025

Someone pointed out in the comments the existence of fnm. It's a drop-in replacement for nvm, written in rust. It's faster and changes nvm versions out of the box when going into a folder that contains an .nvmrc file. I caved and uninstalled nvm, and removed the custom ZSH hook... 😅

Installing fnm on macOS is easy, run brew install fnm and add the following to your .zshrc:

eval "$(fnm env --use-on-cd --shell zsh)"

Bonus: add an alias to prevent annoying typos alias nvm='fnm'

Comments

Join the conversation by sharing on BlueskyBluesky

Could not load comments from Bluesky right now.

Aranet4
Car
Power
NUC