Easiest way to serve production build of a React app over custom domain with HTTPS
This is a deployment of a client-side React application only, which does not need a Node.js environment in server.
Prerequisites
- A Linux server with 80 and 443 ingress ports open.
- A public domain (with a DNS record pointing to the Linux server).
- Basic knowledge of ssh and scp commands.
Building for production and uploading to server
A React app developed using any build tool like Vite or CRA can be built with one command in the root project directory,
npm run build
It will create a dist or build directory in the root project directory.
Then, the directory could be uploaded to server by scp or rsync command, like
scp -r dist username@1.2.3.4:/path/to/upload/directory
Where username should be the server’s username (e.g. root), and 1.2.3.4 would be the server’s hostname (e.g. DNS name or IP address). For Windows, the directory can be uploaded using FTP clients like, FileZilla or WinSCP etc.
For easiest approach, copy or move the dist directory to a root space directory like in /opt. Login using ssh or PuTTY (for Windows), and make a directory in /opt and then copy the folder there.
sudo mkdir /opt/react-app -p
sudo cp -r /path/to/upload/directory/dist /opt/react-app/
Installing and configuring Caddy server
To install the Caddy server follow the official installation documentation for your Linux distribution.
After installation check the status of the Caddy server service if running,
sudo service caddy status
If its running then open the Caddyfile from the /etc/caddy/Caddyfile path with a terminal editor like nano or vim.
sudo nano /etc/caddy/Caddyfile
Comment out or clear the default instructions, and the following lines to the file,
example.com {
root * /opt/react-app/dist
file_server
try_files {path} /index.html
}
Put your domain in place of example.com and restart the Caddy server,
sudo service caddy restart
The website should be accessible on the domain with a SSL certificate from Let’s Encrypt.
Bonus reference
Oracle Cloud provides Always free tier cloud resources, which includes two Compute Instances (Oracle counterpart of EC2). To sign up and create resources follow this article.