How to Host React App on Github Pages
Introduction React has become the de facto standard for building modern, interactive user interfaces. Its component-based architecture, performance optimizations, and vibrant ecosystem make it ideal for everything from simple landing pages to complex single-page applications. But once your React app is built, the next critical step is deployment—specifically, hosting it in a way that is reliable,
Introduction
React has become the de facto standard for building modern, interactive user interfaces. Its component-based architecture, performance optimizations, and vibrant ecosystem make it ideal for everything from simple landing pages to complex single-page applications. But once your React app is built, the next critical step is deploymentspecifically, hosting it in a way that is reliable, fast, and trustworthy.
GitHub Pages is one of the most popular options for hosting static React applications. Its free, integrates seamlessly with Git workflows, and requires no server management. However, many developers encounter issues during deployment: broken routes, missing assets, 404 errors, or inconsistent behavior across browsers. These problems often stem from misconfigurations, lack of understanding of Reacts routing system, or reliance on outdated tutorials.
This guide presents the top 10 trusted, battle-tested methods to host your React app on GitHub Pageseach validated by real-world usage, community feedback, and production deployments. We go beyond basic tutorials to reveal the nuances that separate functional deployments from truly reliable ones. Whether you're a beginner deploying your first portfolio or an experienced developer managing multiple React projects, these methods will help you avoid common pitfalls and ensure your app performs as expected.
Trust in deployment isnt about flashy featuresits about consistency, predictability, and resilience. By the end of this guide, youll know exactly which steps to follow, which configurations to prioritize, and how to troubleshoot issues before they impact your users.
Why Trust Matters
When you host a React application on GitHub Pages, youre not just uploading filesyoure delivering an experience. Users expect fast load times, seamless navigation, and zero errors. A broken link, a 404 on refresh, or a white screen due to misconfigured routing can damage credibility, reduce engagement, and even deter potential employers or clients if its a portfolio project.
Many online tutorials stop at run npm run build, then gh-pages -d build. Thats not enough. That approach ignores critical factors like base URLs, service workers, cache headers, and GitHub Pages limitations with client-side routing. Without addressing these, your app may work locally but fail in production.
Trust is earned through attention to detail. Its knowing that GitHub Pages serves content over HTTPS by default, but doesnt support server-side redirects. Its understanding that React Routers HashRouter is more compatible than BrowserRouter when deploying to subdirectories. Its realizing that the build folder must be committed correctly, and that .nojekyll is required for folders starting with underscores.
Trusted methods dont rely on guesswork. They follow established patterns used by professional developers, open-source projects, and enterprise teams. These methods are documented in official React documentation, GitHubs own guides, and have been tested across multiple browsers and devices.
Additionally, trust includes long-term maintainability. A deployment strategy that works today should still work six months from now. GitHub Pages updates rarely, but Reacts build process evolves. Trusted methods are resilient to version changes in React, Webpack, or Vite. They avoid deprecated tools like the now-archived gh-pages npm package in favor of native GitHub Actions or direct Git workflows.
Finally, trust means security. GitHub Pages enforces HTTPS, but you must ensure your app doesnt load mixed content (HTTP assets on HTTPS pages). Trusted methods verify asset paths, avoid external CDNs without proper CORS, and ensure no sensitive data is exposed in static builds.
In this guide, each of the top 10 methods is selected not just for functionality, but for reliability, scalability, and adherence to industry best practices. You wont find quick hacks hereonly proven strategies that have stood the test of time and real-world usage.
Top 10 How to Host React App on GitHub Pages
Method 1: Use React Router with HashRouter and GitHub Pages
The most reliable method for hosting React apps on GitHub Pages is to use HashRouter instead of BrowserRouter. HashRouter uses the URL hash (
) to simulate a full URL, which prevents GitHub Pages from attempting to route to non-existent server paths.
Start by installing React Router if not already present: npm install react-router-dom. Then, replace your BrowserRouter with HashRouter in your main App.js or index.js file:
import { HashRouter } from 'react-router-dom';
ReactDOM.createRoot(document.getElementById('root')).render(
<HashRouter>
<App />
</HashRouter>
);
Next, build your app: npm run build. Create a new branch named gh-pages or use the default main branch. If using the main branch, go to your repository Settings > Pages and set the source to the / (root) folder and the branch to main.
Push your build folder to GitHub: git add build && git commit -m "Deploy build" and git push. Wait a few minutes, then visit your GitHub Pages URL (e.g., https://username.github.io/repository-name).
This method is trusted because it requires no server-side configuration. GitHub Pages serves static files, and the hash in the URL ensures React Router handles navigation entirely on the client side. Its the default recommendation in the official Create React App documentation for GitHub Pages deployment.
Method 2: Deploy Using GitHub Actions with Automatic Build and Push
Automating your deployment with GitHub Actions eliminates manual steps and reduces human error. This method ensures your app is rebuilt and deployed every time you push to the main branch.
Create a new file in your project: .github/workflows/deploy.yml. Add the following YAML configuration:
name: Deploy React App to GitHub Pages
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Build React App
run: npm run build
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./build
publish_branch: gh-pages
This workflow checks out your code, sets up Node.js, installs dependencies, builds the app, and uses the official actions-gh-pages action to push the build folder to a gh-pages branch.
Go to your repository Settings > Pages and set the source to the gh-pages branch. After pushing to main, the workflow runs automatically. This method is trusted because its fully automated, reproducible, and follows GitHubs recommended patterns. It also supports custom domains and SSL certificates seamlessly.
Method 3: Use Custom Domain with HTTPS and CNAME File
Hosting your React app on a custom domain (e.g., yourapp.com) enhances professionalism and trust. GitHub Pages fully supports custom domains with automatic HTTPS via Lets Encrypt.
First, configure your domains DNS settings. Add an A record pointing to GitHubs IP addresses: 185.199.108.153, 185.199.109.153, 185.199.110.153, and 185.199.111.153. If using a subdomain (e.g., app.yourdomain.com), create a CNAME record pointing to username.github.io.
In your React projects build folder, create a file named CNAME (no extension) and add your custom domain: yourapp.com. Commit and push this file to your deployment branch.
Go to your repository Settings > Pages, scroll to the Custom domain section, and enter your domain. GitHub will automatically provision an SSL certificate. Wait up to 24 hours for DNS propagation and certificate issuance.
This method is trusted because its officially supported by GitHub. It ensures your app loads over HTTPS without warnings, improves SEO, and gives users confidence in your sites legitimacy. Always verify DNS settings using tools like dig or online DNS checkers before relying on this method.
Method 4: Set Correct homepage in package.json for Subdirectory Deployment
If your React app is hosted under a GitHub repository subpath (e.g., https://username.github.io/your-repo), you must configure the homepage field in your package.json file. Failure to do so results in broken asset paths (CSS, JS, images).
Open package.json and add:
"homepage": "https://username.github.io/your-repo-name"
Replace username with your GitHub username and your-repo-name with your actual repository name. Then, rebuild your app: npm run build.
This tells Reacts build system to generate relative paths prefixed with your subdirectory. For example, instead of /static/js/main.js, it generates /your-repo-name/static/js/main.js.
Deploy the build folder to GitHub Pages using any method (Git push, GitHub Actions, etc.). This method is essential for subdirectory deployments and is documented in the official Create React App guide. It prevents 404 errors on asset loading and ensures your app renders correctly.
Method 5: Add .nojekyll File to Bypass Jekyll Processing
GitHub Pages uses Jekyll by default to process static sites. However, Jekyll ignores files and folders that start with an underscore (_). If your React build folder contains assets like _redirects or _assets, they will be skipped, causing broken links.
To bypass Jekyll entirely, create an empty file named .nojekyll in your build folder:
touch build/.nojekyll
Commit and push this file along with your build output. This tells GitHub Pages to serve all files as-is, without attempting to process them with Jekyll.
This method is trusted because its a well-known workaround used by thousands of React, Vue, and Angular developers. Without it, your app may load without styles or scripts, appearing broken. Always include .nojekyll in your deployment process, even if you dont think you need itits a low-effort, high-reward safeguard.
Method 6: Use Vite Instead of Create React App for Faster Builds
While Create React App (CRA) is popular, Vite offers significantly faster build times and better performance for production deployments. Vite is modern, lightweight, and fully compatible with GitHub Pages.
Start a new Vite + React project: npm create vite@latest my-react-app -- --template react. Install dependencies: npm install. Build your app: npm run build.
By default, Vite generates a dist folder. Configure your vite.config.js to set the base path:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
base: '/your-repo-name/' // for subdirectory deployment
})
Deploy the dist folder to GitHub Pages using the same methods as above (Git push or GitHub Actions). Vites build output is optimized, smaller, and loads faster than CRAs. It also supports modern ES modules natively, reducing the need for polyfills.
This method is trusted because Vite is officially recommended by the React team for new projects. Its speed, modern tooling, and compatibility with static hosting make it a superior alternative to CRA for GitHub Pages deployments.
Method 7: Configure Service Workers for Offline Support
GitHub Pages supports service workers, which enable your React app to work offline and improve load times on repeat visits. This is especially valuable for portfolio apps, documentation sites, or PWA-style applications.
If youre using Create React App, the service worker is already included in src/registerServiceWorker.js (CRA v4 and earlier) or src/index.js (CRA v5+). Ensure its not commented out:
import { register } from './registerServiceWorker';
register();
For Vite, install vite-plugin-pwa: npm install -D vite-plugin-pwa. Then configure it in vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
react(),
VitePWA({
registerType: 'autoUpdate',
manifest: {
name: 'Your App',
short_name: 'App',
description: 'A React app hosted on GitHub Pages',
theme_color: '
ffffff',
icons: [
{
src: '/android-chrome-192x192.png',
sizes: '192x192',
type: 'image/png'
},
{
src: '/android-chrome-512x512.png',
sizes: '512x512',
type: 'image/png'
}
]
}
})
],
base: '/your-repo-name/'
})
Build and deploy. Service workers cache assets and enable offline access. This method is trusted because it enhances user experience without requiring backend infrastructure. Its widely used in production by developers who need their apps to remain functional even with intermittent connectivity.
Method 8: Use Environment Variables for Build-Time Configuration
GitHub Pages doesnt support server-side environment variables, but you can use build-time variables to conditionally configure your app. This is useful for API endpoints, analytics keys, or feature flags.
In your .env file, prefix variables with REACT_APP_:
REACT_APP_API_URL=https://api.yourdomain.com
REACT_APP_ANALYTICS_ID=UA-XXXXXXXXX-X
Access them in your code: process.env.REACT_APP_API_URL.
These variables are embedded into the static build during npm run build. They cannot be changed at runtime, but this is perfectly acceptable for GitHub Pages, since the entire app is static.
This method is trusted because it follows Reacts official convention. It keeps sensitive keys out of your source code (when using .env files) and allows you to deploy different builds for staging or production without changing code. Always add .env to your .gitignore to avoid exposing secrets in public repositories.
Method 9: Validate Build Output Before Deployment
Before pushing your build folder to GitHub Pages, always validate it locally. This prevents deploying broken apps and saves hours of debugging.
Install a local HTTP server: npm install -g http-server. Then, from your project root, run: http-server build.
Open http://localhost:8080 in your browser. Test all routes, forms, and interactions. Check the browser console for errors. Verify that assets (CSS, JS, images) load correctly. Look for 404s in the Network tab.
Also, test in incognito mode to ensure no cached data interferes. Use Chrome DevTools to simulate mobile devices and slow network conditions.
This method is trusted because it mimics the production environment before deployment. Many developers skip this step and assume it worked locally, but local development servers behave differently from static file servers. Validation catches 90% of deployment issues before they reach users.
Method 10: Enable GitHub Pages with Custom 404 Page for Better UX
When users refresh a route (e.g., /about) on a React app hosted on GitHub Pages, they often see a GitHub 404 page. This breaks user experience and looks unprofessional.
To fix this, create a custom 404 page that redirects users to your apps index.html. In your build folder, create a file named 404.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Redirecting...</title>
<script>
window.location.href = window.location.origin + window.location.pathname + window.location.search;
</script>
</head>
<body>
<p>Redirecting...</p>
</body>
</html>
This script redirects any 404 request back to the root path, where React Router can handle the route. GitHub Pages automatically serves this file when a page isnt found.
Commit and push 404.html to your deployment branch. This method is trusted because its a widely adopted solution in the React community. It ensures smooth navigation and prevents users from seeing a generic GitHub error page, maintaining the illusion of a full single-page application.
Comparison Table
| Method | Best For | Complexity | Requires Custom Domain | Auto-Deploy | Offline Support | Subdirectory Support | Recommended |
|---|---|---|---|---|---|---|---|
| HashRouter | Beginners, simple apps | Low | No | No | No | Yes (with homepage) | Yes |
| GitHub Actions | Teams, CI/CD pipelines | Medium | No | Yes | Yes (with PWA) | Yes | Yes |
| Custom Domain + CNAME | Professional portfolios, businesses | Medium | Yes | No | Yes (with PWA) | Yes | Yes |
| homepage in package.json | Subdirectory deployments | Low | No | No | No | Yes | Yes |
| .nojekyll file | Any deployment with underscore files | Very Low | No | No | No | Yes | Yes (always use) |
| Vite instead of CRA | Performance-focused apps | Medium | No | Yes | Yes (with PWA) | Yes | Yes |
| Service Workers | PWAs, offline apps | Medium | No | No | Yes | Yes | Yes |
| Environment Variables | Multi-environment configs | Low | No | No | No | Yes | Yes |
| Validate Build Output | All developers | Low | No | No | No | Yes | Yes (mandatory) |
| Custom 404.html | Improved UX, React Router | Low | No | No | No | Yes | Yes |
FAQs
Can I use React Routers BrowserRouter on GitHub Pages?
You can, but it requires additional configuration. BrowserRouter relies on server-side routing to serve index.html for all routes. Since GitHub Pages doesnt support server-side redirects, you must use a custom 404.html file that redirects all requests to index.html. Even then, some edge cases may cause issues. HashRouter is simpler and more reliable.
Why are my CSS and JS files 404ing after deployment?
This usually happens when the homepage field in package.json is missing or incorrect. If your app is hosted at https://username.github.io/my-app, the homepage must be set to that exact URL. Without it, the build generates paths like /static/js/main.js, which GitHub Pages cant find.
Do I need to commit the build folder to GitHub?
Yes, for manual deployments. The build folder contains all static assets required for GitHub Pages to serve your app. However, with GitHub Actions, you only commit the source codethe build folder is generated automatically during the workflow.
How long does it take for GitHub Pages to update after a push?
Typically, changes appear within 12 minutes. If using GitHub Actions, the workflow may take 25 minutes to complete. If changes dont appear after 10 minutes, check the Actions tab for errors and verify your branch settings in repository Settings > Pages.
Can I host multiple React apps on one GitHub account?
Yes. Each repository can have its own GitHub Pages site. Use username.github.io for your personal site (from the repo named username.github.io), and other repositories can be accessed at username.github.io/repo-name.
Is GitHub Pages suitable for production apps?
Yes, for static applications. GitHub Pages is used by many open-source projects, documentation sites, and portfolio apps in production. Its reliable, secure, and free. However, it doesnt support server-side logic, databases, or authentication. For dynamic apps, consider Vercel, Netlify, or AWS Amplify.
Whats the difference between gh-pages branch and main branch for deployment?
GitHub Pages can serve content from the main branch (or master) or a separate gh-pages branch. Using the gh-pages branch keeps your source code and build files separate, which is cleaner. Using the main branch is simpler but mixes source and build files. Both are equally reliable.
How do I fix mixed content warnings (HTTP/HTTPS)?
Ensure all assets (images, fonts, scripts) are loaded over HTTPS. Use relative paths (e.g., /assets/logo.png) or protocol-relative URLs (//example.com/file.js). Avoid hardcoding http:// in your code or config files.
Can I use Firebase or other APIs with my GitHub Pages React app?
Yes. GitHub Pages serves static files, but your React app can make API calls to external services like Firebase, Supabase, or your own backend. Ensure CORS headers are properly configured on the server side.
Why does my app work locally but not on GitHub Pages?
Local development servers (like Webpack Dev Server) handle routing differently than static file servers. Common causes: missing homepage, no .nojekyll, incorrect asset paths, or using BrowserRouter without a 404.html fallback. Use the validation method (Method 9) to test locally before deploying.
Conclusion
Hosting a React app on GitHub Pages is more than a technical taskits a commitment to delivering a seamless, trustworthy experience. The top 10 methods outlined in this guide are not arbitrary suggestions. They are the result of collective developer experience, official documentation, and real-world production deployments.
Each method addresses a specific challenge: routing, automation, performance, security, or user experience. Together, they form a comprehensive framework for deploying React applications with confidence. Whether youre using HashRouter for simplicity, GitHub Actions for automation, or a custom 404.html for better UX, the key is consistency and attention to detail.
Never underestimate the power of small configurationsthe .nojekyll file, the homepage field, or a single service worker can mean the difference between a broken site and a polished product. Trust isnt built through complexity; its built through precision.
As you deploy your next React project, remember that the goal isnt just to get it onlineits to ensure it works flawlessly for every user, every time. Use these trusted methods. Test rigorously. Automate where possible. And always validate before pushing.
GitHub Pages may be simple, but when used correctly, its one of the most powerful and reliable tools at a developers disposal. With the knowledge in this guide, youre no longer just deploying codeyoure delivering digital experiences that users can rely on.