Build & Host React App for FREE using GitHub Pages ๐
After creating your React project, the next important step is deployment.
Instead of keeping your project only on localhost, you can host it online for free ๐
GitHub Pages allows you to deploy your React app easily without any cost.
In this tutorial, we will learn:
Step 1: Build React App
Before deploying, you need to create an optimized production build of your app.
npm run build
This command will create a build folder containing all optimized files.
Step 2: Install GitHub Pages Package
Install the gh-pages package to help deploy your app.
npm install gh-pages --save-dev
Step 3: Update package.json
Add homepage and deployment scripts inside your package.json.
"homepage": "https://your-username.github.io/your-repo-name",
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
Step 4: Initialize Git & Push to GitHub
If not already done, initialize Git and push your project to GitHub.
git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/your-username/your-repo-name.git
git push -u origin main
Step 5: Deploy React App ๐
Now run the deploy command:
npm run deploy
After a few seconds, your app will be live at:
https://your-username.github.io/your-repo-name
Step 6: Enable GitHub Pages
Go to your GitHub repository โ Settings โ Pages Select branch: gh-pages and save.
---Important Note โ ๏ธ
If you are using React Router, add this in your package.json:
"homepage": "."
Or use HashRouter instead of BrowserRouter to avoid routing issues.