Rails 6 & Node: Yarn error on install around ‘remove_cv_t’

This error can occur when setting up a development environment for an existing Rails 6 project and the node dependencies are being installed. It seems to be caused by an incompatibility between node-sass and Node 16.

Here are step by step instructions on how to fix the problem by specifying the version of node to use in the project folder using NVM.

➜ bundle exec rails server # rails won't boot, yarn error
...
========================================
  Your Yarn packages are out of date!
  Please run `yarn install --check-files` to update.
========================================

➜ yarn install --check-files # yarn install fails...
...
/Users/user/.node-gyp/16.13.1/include/node/v8-internal.h:492:38: error: no template named 'remove_cv_t' in namespace 'std'; did you mean 'remove_cv'?

➜ brew install nvm # install Node Version Mgr if needed
➜ echo "14.18.2" > .nvmrc # create a version file for NVM (do this in your rails project directory)
➜ cat .nvmrc
14.18.2

➜ node -v # check the current node version
v16.13.1

➜ nvm use
Found '/Users/user/project/.nvmrc' with version <14.18.2>
Now using node v14.18.2 (npm v6.14.15)

➜ node -v # verify we're now using the correct node version
v14.18.2

➜ yarn install --check-files # install should now complete ok
...
✨  Done in 8.73s.

➜ bundle exec rails server # rails should now boot
=> Booting Puma

Here’s the full error trace:

In file included from /Users/user/.node-gyp/16.13.1/include/node/v8.h:30:
/Users/user/.node-gyp/16.13.1/include/node/v8-internal.h:492:38: error: no template named 'remove_cv_t' in namespace 'std'; did you mean 'remove_cv'?
            !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
                                ~~~~~^~~~~~~~~~~
                                     remove_cv
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/type_traits:710:50: note: 'remove_cv' declared here
template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_cv
                                                 ^
1 error generated.
make: *** [Release/obj.target/binding/src/binding.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/user/project/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
gyp ERR! System Darwin 21.2.0
gyp ERR! command "/Users/user/.nvm/versions/node/v16.13.1/bin/node" "/Users/user/project/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /Users/user/project/node_modules/node-sass
gyp ERR! node -v v16.13.1
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok