Automatically use the correct node version with zsh and nvm

I like to use nvm to manage the node version on my machine and therefore it is only logical to have also a .nvmrc file in projects, which I use to set the appropriate node version.

In this project it is about the current LTS version of node:


Now when I switch projects I could just run nvm use to load the version, but honestly I tend to forget to do that. Fortunately, this can be quickly corrected with a tweak in my ~/.zshrc (I use Zsh and Oh My Zsh). After the initialization of nvm you just have to insert the following code:

# place this after nvm initialization!
autoload -U add-zsh-hook
load-nvmrc() {
  local node_version="$(nvm version)"
  local nvmrc_path="$(nvm_find_nvmrc)"

  if [ -n "$nvmrc_path" ]; then
    local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")

    if [ "$nvmrc_node_version" = "N/A" ]; then
      nvm install
    elif [ "$nvmrc_node_version" != "$node_version" ]; then
      nvm use
  elif [ "$node_version" != "$(nvm version default)" ]; then
    echo "Reverting to nvm default version"
    nvm use default
add-zsh-hook chpwd load-nvmrc

You can find that in the official doc to nvm, but who ever reads instructions 😅