Article posted Thu Mar 02 2023 Updated Sun Mar 05 2023

Scripts: Deploying ReactJS with Apache

First, Apache needs to be run as a reverse proxy, for requests on port 3000. This is the default port node will be running on. We need to install two Apache2 mods; mod_proxy and mod_proxy_http.

There is also mod_proxy_balancer, mod_proxy_connect and mod_proxy_html available for further configuration.
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo service apache2 restart

The related site conf file will need updating to use these new mods. Add the following to the apache conf (sites-available) to proxy to port 3000 on localhost;

ProxyRequests off

<Proxy *>
        Order deny,allow
        Allow from all
</Proxy>

<Location />
        ProxyPass http://localhost:3000/
        ProxyPassReverse http://localhost:3000/
</Location>

Making deployment easier

The bash script below, when placed into the projects root, is an example of updating using a repository manager like git. The script will then destroy the <project dir>/build folder, run npm to rebuild, apply permissions and re-deploy node if needed. There are likely much more elegant solutions, but the below is an example of how this can be achieved in a simple script. This script assumes all proxy/routing for Apache has been set up beforehand.

#!/bin/bash

# Prompt the user for confirmation before continuing
read -p "This script will execute git pull origin main, delete the build directory, run npm run build, copy the build directory to /var/www/html/, and restart the server. Are you sure you want to continue? (y/n) " confirm

if [[ "$confirm" != "y" ]]; then
  echo "Aborting script."
  exit 1
fi

# Get the current working directory and print it to the screen
pwd
read -p "Please confirm that you are in the correct directory. Continue? (y/n) " confirm

if [[ "$confirm" != "y" ]]; then
  echo "Aborting script."
  exit 1
fi

# Pull the latest changes from the main branch
git pull origin main

# Remove the build directory
rm -rf build/

# Build the project
npm run build

# Copy the build directory to the web server directory
cp -r /var/www/move_from_directory/build/ /var/www/move_to_directory/

# Set the correct permissions for the web server user
chown -R www-data:www-data /var/www/html/

# Kill any running Node processes
ps aux | grep node
read -p "Enter the PID of the Node process you want to kill (or leave blank to skip): " pid

if [[ -n "$pid" ]]; then
  kill "$pid"
  # Restart the server
  nohup npm start &
fi