Hosting a React.js website on a shared server with cPanel involves a series of steps to ensure a smooth deployment. Below is an easy guide on how to host a React.js website on a shared server using cPanel.
Prerequisites:
- Shared Hosting Account: Ensure you have access to a shared hosting account with cPanel.
- Node.js and npm: Make sure Node.js and npm are installed on your local machine.
- React App: Have your React.js application ready for deployment.
Step 1: Build Your React App
Before deployment, build your React app to create the production-ready build. Open your terminal and navigate to your project folder, then run:
npm run build
This command generates a build
folder containing optimized and minified files.
Step 2: Access cPanel
- Log in to your cPanel account provided by your hosting provider.
- Navigate to the “File Manager” to manage your files.
Step 3: Upload Files to the Server
- In the “File Manager,” go to the
public_html
directory. - Upload the contents of the
build
folder (excluding the folder itself) intopublic_html
. You can use the cPanel file uploader or an FTP client.
Step 4: Create .htaccess
File
- Create a new file named
.htaccess
in thepublic_html
directory. - Edit the file and add the following code to enable the server to handle React Router:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
Step 5: Set Up Node.js
- In cPanel, locate the “Setup Node.js App” option.
- Create a new Node.js application:
- Choose the Node.js version.
- Set the application root to
public_html
. - Set the application URL to your domain.
- Start the application.
Step 6: Update npm Packages
In the cPanel terminal, navigate to your public_html
folder and run:
npm install --production
Step 7: Update Environment Variables
If your React app uses environment variables, update them in your cPanel account or directly in the .htaccess
file.
Step 8: Test Your Website
Visit your domain in a web browser to test your React.js website. Ensure that routing works correctly.
Conclusion:
Hosting a React.js website on a shared server with cPanel involves uploading your build files, configuring the server to handle React Router, and setting up Node.js if needed. Follow the steps carefully to ensure a successful deployment of your React app.