GitHub Pages provides a free, reliable hosting solution for React applications, making it an ideal choice for personal projects, portfolios, documentation sites, and small-to-medium web applications. This comprehensive guide covers everything you need to deploy your React app to GitHub Pages, from basic setup to advanced configurations including automated deployments with GitHub Actions and custom domain configuration.
For teams building modern web applications, understanding deployment pipelines is essential. Our web development services team regularly implements deployment strategies that scale from simple static sites to complex React applications.
Key benefits that make GitHub Pages an excellent choice for hosting React applications
Free Hosting
No cost for hosting static websites with HTTPS included automatically
GitHub Integration
Direct integration with your GitHub repository for seamless deployment workflows
Custom Domains
Support for custom domain names with automatic SSL certificate provisioning
CDN Distribution
Global content delivery through GitHub's infrastructure for fast load times
Preparing Your React App for Deployment
Before deploying to GitHub Pages, your React application needs proper configuration. The build process compiles your React code into optimized static files that can be served by any web server.
The Production Build Process
When you run npm run build, Create React App or Vite creates an optimized production build of your application:
- Minified and bundled JavaScript files
- Compressed CSS assets
- Optimized images and static resources
- A single index.html file that serves as the entry point
- Fingerprinted filenames for cache busting
The build output resides in a build or dist folder and contains everything needed to serve your application.
Setting the Homepage in package.json
One of the most important configurations is setting the correct homepage in your package.json:
{
"homepage": "https://yourusername.github.io/repository-name"
}
Critical: This field determines the base URL for all asset references in the built HTML. Incorrect configuration leads to broken links and missing assets.
Understanding how Node.js handles file systems and path operations is crucial when configuring build scripts and deployment processes.
1{2 "name": "my-react-app",3 "version": "1.0.0",4 "homepage": "https://username.github.io/my-react-app",5 "scripts": {6 "start": "react-scripts start",7 "build": "react-scripts build",8 "test": "react-scripts test",9 "eject": "react-scripts eject",10 "predeploy": "npm run build",11 "deploy": "gh-pages -d build"12 },13 "dependencies": {14 "react": "^18.2.0",15 "react-dom": "^18.2.0",16 "react-router-dom": "^6.20.0"17 }18}Deploying with the gh-pages Package
The gh-pages npm package provides a straightforward way to deploy your React application to GitHub Pages from the command line.
Installing gh-pages
npm install --save-dev gh-pages
# or
yarn add -D gh-pages
How Deployment Works
The npm run deploy command performs the following steps:
- Runs
npm run buildto create the production build - Initializes a temporary git repository in the build directory
- Commits the build files
- Pushes to the
gh-pagesbranch on your GitHub repository
For user sites deployed from the main branch:
{
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -b main -d build"
}
}
The -b main flag specifies which branch to deploy to.
When building larger applications, consider implementing code splitting to reduce bundle sizes and improve initial load times.
Environment Variables and API Endpoints
For applications that interact with external services, understanding how compression streams APIs work can help optimize data transfer and reduce bandwidth costs when deploying to static hosting platforms.
Automated Deployments with GitHub Actions
GitHub Actions enables automated deployments triggered by code changes, eliminating manual deployment steps and ensuring consistent release processes.
Creating a Deployment Workflow
Create a .github/workflows/deploy.yml file:
name: Deploy to GitHub Pages
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Setup Pages
uses: actions/configure-pages@v4
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: 'build'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
Benefits of Automated Deployments
- Consistent deployment process without manual steps
- Automatic builds on every push to main
- Preview deployments for pull requests
- Built-in caching for faster builds
- Audit trail of all deployments
For organizations managing multiple React projects, our web development services can help set up comprehensive CI/CD pipelines.
Stay current with modern development by exploring our guide on Node.js 24 new features to leverage the latest Node.js capabilities in your deployment workflows.
Handling Client-Side Routing
One of the most common challenges when deploying React applications with client-side routing is ensuring the server correctly handles deep links and refresh scenarios.
The Routing Challenge
When a user visits a URL like /todos/42 directly, the GitHub Pages server looks for a file at that path. Since React applications are single-page applications, that file doesn't exist, resulting in a 404 error.
Solution 1: Using HashRouter
HashRouter uses the URL hash to manage routing, which works well with GitHub Pages:
import { HashRouter as Router, Routes, Route } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/todos/:id" element={<TodoDetail />} />
</Routes>
</Router>
);
}
URLs will look like: https://username.github.io/repo/#/todos/42
Solution 2: Configuring 404 Redirection
For BrowserRouter, create a public/404.html file that redirects to index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Redirecting...</title>
<script>
(function() {
var path = window.location.pathname;
var search = window.location.search;
var hash = window.location.hash;
window.location.href = '/' + (path.slice(1) || '') + (search || '') + (hash || '');
})();
</script>
</head>
<body></body>
</html>
Understanding how HTML text area elements and advanced text features work in modern web applications helps build better user experiences with client-side routing.
Building e-commerce applications? Learn how to handle routing in B2B eCommerce websites with similar client-side routing challenges.
Custom Domains with GitHub Pages
GitHub Pages supports custom domains, allowing you to host your React application on your own domain name.
Adding a CNAME File
Create a public/CNAME file containing your custom domain:
my-awesome-app.com
www.my-awesome-app.com
DNS Configuration
For apex domains, add A records pointing to GitHub's IP addresses:
- 185.199.108.153
- 185.199.109.153
- 185.199.110.153
- 185.199.111.153
For www subdomains, create a CNAME record:
- Name: www
- Value: yourusername.github.io
Enabling HTTPS
GitHub Pages automatically provisions SSL certificates through Let's Encrypt for custom domains.
For high-performance deployments, consider our React development services to optimize both build times and runtime performance.
Learn more about web performance optimization to ensure your deployed applications deliver excellent user experiences.
Performance Optimization for Production
Optimizing your React application ensures fast load times and good user experience on GitHub Pages.
Code Splitting
Use React's lazy loading to split your code into smaller chunks:
import { lazy, Suspense } from 'react';
const HeavyComponent = lazy(() => import('./HeavyComponent'));
function App() {
return (
<Suspense fallback={<Loading />}>
<HeavyComponent />
</Suspense>
);
}
Asset Optimization
- Use WebP or optimized image formats
- Compress images before adding to the project
- Lazy load below-the-fold images
- Use SVGs for icons and simple graphics
Build Analysis
Analyze bundle sizes to identify optimization opportunities:
npm install --save-dev source-map-explorer
npx source-map-explorer 'build/static/js/*.js'
For teams working with the latest Node.js features, explore our guide on Node.js 24 new features to stay current with modern development practices.
Understanding how the CSS Custom Highlight API and generated content can enhance your application's visual presentation without compromising performance.
Frequently Asked Questions
Is GitHub Pages free for commercial use?
Yes, GitHub Pages is free for both personal and commercial use. There are no bandwidth charges for GitHub Pages traffic.
What is the difference between user sites and project sites?
User sites are limited to one per account and deployed from the main branch. Project sites are unlimited per account and deployed from the gh-pages branch or docs folder.
Can I use React Router with GitHub Pages?
Yes, but you need to use HashRouter or configure a 404.html redirect for BrowserRouter to handle direct URL access and page refreshes correctly.
How long does it take for changes to appear after deployment?
Changes typically appear within a few seconds to a minute after pushing to GitHub, depending on the deployment method and caching.
Can I use a custom domain with HTTPS?
Yes, GitHub Pages automatically provisions SSL certificates through Let's Encrypt for custom domains at no additional cost.