Quick Fix For Node Upgrade Script On Laravel Forge

Recently while upgrading an older Laravel project to the latest version of Laravel, I switched out the frontend build tool from Laravel Mix to Vite. This switch also required upgrading the version of Node.js on the production server, so that Vite could run properly and build out the project's assets.

The Laravel Forge docs provide a handy "Cookbook" page with information on how to handle common issues, including scripts for upgrading different tools on your server. You can run these scripts manually on your server after you SSH in, or within the Forge user interface, you can add them to your executable "recipes" that you can trigger and run on any or all of your Forge provisioned servers; thus the "cookbook" analogy.

Anyhoo, I ended up running the recommended script for Upgrading Node.js, but each time I ran the script, it failed. The logs indicated some odd information about a "certificate" and "gpg key", but the basic gist was that it did not work, and I was stuck on the older version of Node.js.

Turns out, the script is based on the instructions provided by the NodeSource Node.js Binary Distributions installation instructions, and upon comparing them, I found there was a command missing from the script in the Forge docs:

# Command missing from the Laravel Forge Cookbook script
sudo mkdir -p /etc/apt/keyrings

This command creates the directory where the the Nodesource GPG key is imported. Without the directory, the key is not imported and the rest of the script does not execute properly.

Below is the full script that you can add to your Laravel Forge account as a Recipe and run to upgrade Node.js:

sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg

echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list

sudo apt-get update
sudo apt-get install nodejs -y

NODE_MAJOR=20 specifies the version of Node.js you are looking to install.

Maybe the original Forge script expects that directory to already exist? It definitely did not on my server and threw me for a whirl during my production deploy! I plan on reaching out to the Laravel Forge team to let them know just in case it is a mistake.

Hope this helps someone else that runs into a similar situation when upgrading Node.js on their server!