Hosting /Deploying React js app with Nginx

Get 200$ in Digital Ocean and Get 100$ in Vultr

make sure you use ubuntu server and once you logged in you can follow following commands.

Install Nginx

sudo apt install nginx -y

Install node using NVM

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.bashrc
nvm install node
node --version

Clone React js sample app and setup

git clone https://github.com/fluxxset/react-sample.git /var/www/react-sample
cd my-react-app/
npm install 
npm install -g serve
npm run build

test if app is working

serve -s build -l 8000

Creating service file for deployment

nano /etc/systemd/system/react.service

add following content in file

[Unit]
Description=React daemon
After=network.target

[Service]
User=root
Group=root
WorkingDirectory=/var/www/react-sample/my-react-app
ExecStart=/bin/bash -c 'source /home/ubuntu/.nvm/nvm.sh && nvm use 21.6.2 && cd /var/www/react-sample/my-react-app && /home/ubuntu/.nvm/versions/node/v21.6.2/bin/serve -s build -l 3000'




[Install]
WantedBy=multi-user.target

Configure Nginx

Update /etc/nginx/sites-available/default:

nano /etc/nginx/sites-available/default

Add the following:

server {
    listen 80;

    location / {
        include proxy_params;
        proxy_pass 127.0.0.1:8000
    }
}


Finally, restart and enable services:

# Reload systemd daemon
sudo systemctl daemon-reload

# Enable  service 
sudo systemctl enable react  

# Start 
sudo systemctl start react

# Restart nginx 
sudo service nginx restart

Now, go to your browser, type the Domain , and you should see your React website running.