How to Host React App on Github Pages
How to Host React App on GitHub Pages Hosting a React application on GitHub Pages is one of the most accessible and cost-effective ways to deploy modern web applications. Whether you're a developer building a personal portfolio, a startup showcasing a prototype, or a student demonstrating a class project, GitHub Pages offers a seamless, free, and reliable platform to make your React app publicly a
How to Host React App on GitHub Pages
Hosting a React application on GitHub Pages is one of the most accessible and cost-effective ways to deploy modern web applications. Whether you're a developer building a personal portfolio, a startup showcasing a prototype, or a student demonstrating a class project, GitHub Pages offers a seamless, free, and reliable platform to make your React app publicly accessible. Unlike traditional hosting services that require server configuration, domain purchases, or complex deployments, GitHub Pages allows you to publish static content directly from a GitHub repository with minimal setup.
React apps, by nature, are static once built. The build process generates HTML, CSS, and JavaScript files that can be served by any static file server making GitHub Pages an ideal candidate. This tutorial provides a comprehensive, step-by-step guide to deploying your React application to GitHub Pages, including best practices, troubleshooting tips, and real-world examples to ensure your deployment is smooth, scalable, and SEO-friendly.
By the end of this guide, youll understand not only how to host your React app on GitHub Pages, but also how to optimize it for performance, handle routing correctly, and maintain a professional online presence all without spending a dime.
Step-by-Step Guide
Prerequisites
Before you begin, ensure you have the following:
- A GitHub account (free at github.com)
- Node.js and npm (or yarn) installed on your machine
- A React project (created with Create React App, Vite, or another React framework)
- Basic familiarity with the command line and Git
If you dont already have a React project, create one using Create React App:
npx create-react-app my-react-app
cd my-react-app
Or, if you prefer Vite:
npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install
Once your project is ready, you can proceed with deployment.
Step 1: Initialize a Git Repository
If your React project isnt already under version control, initialize a Git repository:
git init
git add .
git commit -m "Initial commit"
This step is essential because GitHub Pages pulls content directly from a Git repository. Without Git, you cannot proceed with deployment.
Step 2: Create a GitHub Repository
Log in to your GitHub account and click the New button to create a repository.
There are two naming conventions for GitHub Pages repositories:
- User or Organization Site:
username.github.ioThis deploys tohttps://username.github.ioand can only have one per account. - Project Site:
repository-nameThis deploys tohttps://username.github.io/repository-name. You can have multiple project sites.
For this tutorial, well assume youre deploying a project site. Name your repository something like my-react-app. Do not initialize it with a README, .gitignore, or license youll push your local files instead.
Step 3: Add the Remote Repository
In your local project directory, link it to the newly created GitHub repository:
git remote add origin https://github.com/your-username/your-repo-name.git
Replace your-username and your-repo-name with your actual GitHub username and repository name.
Step 4: Configure React for GitHub Pages
By default, Create React App assumes your app will be served from the root path (/). However, when deployed to GitHub Pages as a project site, your app will be served from a subpath like /my-react-app/. This causes broken links and routing issues.
To fix this, you need to configure the homepage field in your package.json file.
Open package.json and add or update the homepage property:
{
"name": "my-react-app",
"version": "0.1.0",
"private": true,
"homepage": "https://your-username.github.io/your-repo-name",
"dependencies": {
...
},
"scripts": {
...
}
}
Replace your-username and your-repo-name with your actual GitHub username and repository name.
For a user site (e.g., username.github.io), set:
"homepage": "https://your-username.github.io"
This tells React to generate relative paths during the build process, ensuring all assets (CSS, JS, images) are correctly referenced under the subpath.
Step 5: Install gh-pages Package
The gh-pages package is a Node.js tool that automates the deployment of your built React app to the gh-pages branch on GitHub.
Install it as a development dependency:
npm install gh-pages --save-dev
Or if you're using yarn:
yarn add gh-pages --dev
Step 6: Update npm Scripts
In your package.json, update the scripts section to include deployment commands:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
Heres what each script does:
predeployruns automatically beforedeployand ensures your app is built before uploading.deployusesgh-pagesto push the contents of thebuildfolder to thegh-pagesbranch on GitHub.
If youre using Vite, your build command is vite build, so adjust accordingly:
"scripts": {
"dev": "vite",
"build": "vite build",
"predeploy": "npm run build",
"deploy": "gh-pages -d dist"
}
For Vite, the output folder is dist instead of build.
Step 7: Push to GitHub
Commit your changes to your local repository:
git add .
git commit -m "Configure GitHub Pages deployment"
Push to the main branch (or master, depending on your default branch):
git branch -M main
git push -u origin main
If your default branch is master, use:
git push -u origin master
Step 8: Deploy to GitHub Pages
Now, deploy your app with a single command:
npm run deploy
When you run this command:
- It automatically runs
npm run buildto generate the production-ready files in thebuildfolder. - It creates a new branch called
gh-pagesin your GitHub repository (if it doesnt exist). - It pushes all files from the
buildfolder into thegh-pagesbranch.
Youll see output in your terminal confirming the deployment. After a few moments, GitHub Pages will process the files and make your site live.
Step 9: Verify Deployment
Go to your GitHub repository on the web, click the Settings tab, then scroll down to the Pages section.
Under Source, you should see:
- Branch:
gh-pages - Folder:
(root)
GitHub Pages will display a green checkmark and a live URL. Click it to open your deployed React app.
It may take 12 minutes for the site to become available. If you see a 404, wait a few more minutes and refresh.
Step 10: Update Your App (Future Deployments)
After the initial deployment, every time you make changes to your React app:
- Make your code changes locally.
- Run
npm run buildto regenerate the production build. - Commit your changes:
git add . && git commit -m "Update app" - Push to main:
git push origin main - Run
npm run deployagain.
The gh-pages branch will automatically update with the new build, and your live site will reflect the changes.
Best Practices
Use Relative Paths in Your App
Even though setting the homepage field in package.json handles most path issues, ensure your internal links (e.g., image sources, asset imports) use relative paths or are imported via JavaScript.
Avoid hardcoding absolute URLs like:
<img src="https://example.com/logo.png" />
Instead, use:
import logo from './assets/logo.png';
<img src={logo} alt="Logo" />
This ensures assets are bundled and referenced correctly during the build process.
Enable Caching for Better Performance
GitHub Pages serves static files with default caching headers. To optimize performance, you can add a CNAME file to your build folder (or configure it via GitHub settings) if youre using a custom domain.
For better caching, consider adding a .nojekyll file to the root of your build folder. This tells GitHub Pages not to process your site with Jekyll, which can interfere with React apps.
Create the file manually:
touch build/.nojekyll
Then ensure its included in your deployment by adding it to your repository before running npm run deploy.
Handle Client-Side Routing Correctly
React Router (or any client-side routing library) relies on the browsers History API. When users refresh the page on a route like /about, GitHub Pages looks for a file at /about/index.html, which doesnt exist resulting in a 404.
To fix this, create a 404.html file in your public folder that redirects all unmatched routes to /index.html.
Inside public/404.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="refresh" content="0; url=/your-repo-name/">
</head>
<body>
<p>Redirecting...</p>
</body>
</html>
Replace /your-repo-name/ with your actual repository path (e.g., /my-react-app/).
Alternatively, use the basename prop in React Router to handle subpaths:
import { BrowserRouter } from 'react-router-dom';
function App() {
return (
<BrowserRouter basename="/your-repo-name">
<AppRoutes />
</BrowserRouter>
);
}
This ensures React Router knows the base URL and generates correct links.
Optimize Build Output
Reacts default build process generates large, unminified assets. To reduce load times:
- Use
react-scripts build(orvite build) it automatically minifies code and bundles assets. - Enable code splitting using dynamic imports:
import('./Component').then(...). - Optimize images using tools like
sharporsquoosh. - Remove unused dependencies and libraries.
You can also use tools like source-map-explorer to analyze bundle sizes:
npm install source-map-explorer --save-dev
npx source-map-explorer build/static/js/*.js
Use HTTPS
GitHub Pages automatically provides HTTPS for all sites. Ensure your React app doesnt make HTTP requests to external APIs use relative URLs or HTTPS endpoints. Modern browsers block mixed content, which can break your app.
Test Locally Before Deploying
Before deploying, test your production build locally:
npm run build
npx serve -s build
This serves your built app on http://localhost:5000 and simulates the production environment. Check all routes, images, and functionality before pushing to GitHub.
Monitor Deployment Status
GitHub Pages provides build logs. If your site fails to deploy, go to your repository ? Settings ? Pages ? and check the Build and deployment section for error messages.
Common errors include:
- Incorrect
homepageURL - Missing
gh-pagesbranch - Build failure due to syntax errors
- Incorrect folder path in
gh-pages -d build
Tools and Resources
Essential Tools
- gh-pages The Node.js package used to deploy to GitHub Pages. Automatically handles branch creation and file pushing.
- Create React App The official React boilerplate with built-in build scripts and configuration.
- Vite A faster alternative to Create React App with better performance and modern tooling.
- source-map-explorer Analyzes bundle sizes to help optimize performance.
- Squoosh A web-based image compression tool to reduce asset sizes without quality loss.
- Lighthouse Chrome DevTools extension to audit performance, accessibility, SEO, and best practices.
GitHub Pages Documentation
Always refer to the official documentation for the most accurate and up-to-date information:
Alternative Deployment Tools
While GitHub Pages is free and simple, consider these alternatives for more advanced needs:
- Vercel Optimized for React, automatic CI/CD, preview deployments, and edge network.
- Netlify Drag-and-drop deployment, form handling, serverless functions, and custom domains.
- Render Free tier with continuous deployment and SSL.
- Cloudflare Pages Fast global CDN, built-in CI/CD, and integrations with GitHub.
These platforms often provide better performance, automatic builds on push, and more robust routing but come with a learning curve and may require credit cards for advanced features.
Custom Domain Setup
To use a custom domain (e.g., myapp.com) instead of username.github.io:
- Go to your GitHub repository ? Settings ? Pages.
- Under Custom domain, enter your domain name (e.g.,
myapp.com). - Save.
- Go to your domain registrar (e.g., Namecheap, GoDaddy) and set up DNS records:
- A record pointing to
185.199.108.153 - A record pointing to
185.199.109.153 - A record pointing to
185.199.110.153 - A record pointing to
185.199.111.153
GitHub will automatically provision an SSL certificate for your custom domain.
Real Examples
Example 1: Personal Portfolio
A developer named Alex built a React portfolio using Create React App. He:
- Set
homepageto"https://alexdev.github.io/portfolio" - Installed
gh-pagesand added deployment scripts - Created a
public/404.htmlfile to handle routing - Pushed to GitHub and ran
npm run deploy
Result: https://alexdev.github.io/portfolio Live, fast, and fully functional with React Router.
Example 2: Open-Source Dashboard
A team built a React-based analytics dashboard for their open-source project. They:
- Used Vite for faster builds
- Configured
homepageas"https://teamname.github.io/analytics-dashboard" - Added a
.nojekyllfile to prevent Jekyll interference - Set up GitHub Actions to auto-deploy on every push to main
They used a GitHub Actions workflow to automate deployment:
name: Deploy to GitHub Pages
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: npm run build
- uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./dist
This eliminated manual deployment and ensured every code change triggered an automatic update.
Example 3: Student Project Submission
A university student deployed a React-based weather app for a final project:
- Used Create React App
- Set homepage to
"https://studentname.github.io/weather-app" - Added a README.md with a live link and screenshots
- Used Lighthouse to achieve a performance score of 95+
The instructor was impressed by the clean deployment and performance all achieved with free tools.
FAQs
Can I host a React app with API calls on GitHub Pages?
Yes, but only if the API is publicly accessible and supports CORS. GitHub Pages serves only static files. Any backend logic (e.g., Node.js, databases) must be hosted elsewhere (e.g., Firebase, Supabase, Vercel Functions). Your React app can make HTTP requests to these external services.
Why is my React app blank after deploying to GitHub Pages?
This usually happens due to:
- Incorrect
homepagesetting inpackage.json - Missing or misconfigured
404.htmlfile for routing - Hardcoded absolute URLs in your code
- Build errors that didnt show in development
Check the browser console for 404s or JavaScript errors, and verify your homepage matches your repository path.
Do I need to pay for GitHub Pages?
No. GitHub Pages is completely free for public repositories. Private repositories require a paid GitHub plan for Pages hosting.
Can I use GitHub Pages for production apps?
Yes, many production apps use GitHub Pages successfully especially for marketing sites, documentation, and lightweight dashboards. However, for high-traffic applications or those requiring server-side logic, consider platforms like Vercel or Netlify for better scalability and features.
How do I update my React app after deployment?
Simply make changes locally, run npm run build, commit your code, push to main, and run npm run deploy again. The gh-pages branch will be updated automatically.
Why is my custom domain not working?
Common reasons:
- DNS records havent propagated (wait up to 48 hours)
- Incorrect A records or missing CNAME record
- Domain registrar requires additional verification
- GitHub Pages hasnt issued an SSL certificate yet
Check GitHubs Pages settings for status messages and verify your DNS configuration using tools like DNS Checker.
Does GitHub Pages support server-side rendering (SSR)?
No. GitHub Pages is a static hosting service. It cannot run Node.js servers or execute server-side code. For SSR, use Vercel, Netlify, or Render with Next.js.
Can I deploy multiple React apps to the same GitHub account?
Yes. You can create multiple repositories (e.g., app1, app2) and deploy each to its own GitHub Pages URL: username.github.io/app1, username.github.io/app2, etc.
Conclusion
Hosting a React app on GitHub Pages is a powerful, free, and straightforward way to share your work with the world. From personal projects to open-source tools, this deployment method removes barriers to entry and empowers developers to focus on building not configuring servers.
By following the steps outlined in this guide configuring the homepage, installing gh-pages, handling routing with 404.html, and testing locally you ensure your app loads correctly and performs well. Best practices like optimizing assets, enabling HTTPS, and automating deployments with GitHub Actions further elevate your projects professionalism.
While GitHub Pages has limitations primarily its static nature it remains one of the most reliable and beginner-friendly deployment options available. As your projects grow, you may outgrow it and migrate to platforms like Vercel or Netlify. But for most use cases, GitHub Pages provides everything you need: speed, simplicity, and zero cost.
Now that youve mastered deploying React apps to GitHub Pages, your next step is to showcase your work. Build something meaningful, deploy it, and share the link. The web is waiting.