How to Deploy React App to GitHub Pages Quickly
To deploy a React app to GitHub Pages, add the
homepage field in package.json with your GitHub repo URL, install gh-pages, then run npm run deploy after adding deploy scripts. This publishes your app to GitHub Pages automatically.Syntax
Deploying a React app to GitHub Pages involves these key parts:
- homepage: Add this field in
package.jsonwith your GitHub Pages URL. - scripts: Add
predeployanddeployscripts to automate build and publish. - gh-pages: A package that handles pushing the build folder to the
gh-pagesbranch.
json
{
"homepage": "https://yourusername.github.io/your-repo-name",
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
}Example
This example shows how to set up and deploy a React app to GitHub Pages step-by-step.
bash
1. Create React app: npx create-react-app my-app 2. Change directory: cd my-app 3. Install gh-pages: npm install gh-pages --save-dev 4. Edit <code>package.json</code>: { "homepage": "https://yourusername.github.io/my-app", "scripts": { "start": "react-scripts start", "build": "react-scripts build", "predeploy": "npm run build", "deploy": "gh-pages -d build" } } 5. Deploy: npm run deploy 6. Go to GitHub repo settings > Pages and ensure source is set to <code>gh-pages</code> branch.
Output
Creating an optimized production build...
Uploading to GitHub Pages...
Published
Common Pitfalls
- Not setting the
homepagefield causes broken links on GitHub Pages. - Forgetting to install
gh-pagesor adding deploy scripts will fail deployment. - Deploying without building first will publish an empty or old site.
- Not setting GitHub Pages source branch to
gh-pagesin repo settings prevents site from showing.
json
Wrong (missing homepage):
{
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
}
Right (with homepage):
{
"homepage": "https://yourusername.github.io/my-app",
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
}Quick Reference
Summary tips for deploying React apps to GitHub Pages:
| Step | Description |
|---|---|
| Add homepage | Set "homepage" in package.json to your GitHub Pages URL |
| Install gh-pages | Run npm install gh-pages --save-dev |
| Add scripts | Add predeploy and deploy scripts in package.json |
| Deploy | Run npm run deploy to build and publish |
| Set GitHub Pages source | In repo settings, choose gh-pages branch |
Key Takeaways
Always set the homepage field in package.json to your GitHub Pages URL.
Use gh-pages package with predeploy and deploy scripts to automate deployment.
Run npm run deploy to build your app and publish it to GitHub Pages.
Check GitHub repo settings to ensure Pages source is set to gh-pages branch.
Common errors come from missing homepage or incorrect branch settings.