Introduction
I've seen many of my peers and college mates pulling their hair out over choosing a host service just to get their React app online. I always tell them there's a better way—GitHub Pages! It's free, straightforward, and even supports custom domains.
My personal website, which has all sorts of cool features like a portfolio, admin login, quick quote share, and URL shortener, is hosted on GitHub Pages and uses my custom domain rpkr.in, complete with an SSL certificate. It's easier than you'd think!
Pre-requistes
Before diving in! Make sure you’ve got the following checked off:
- Your React app is built using Create React App. If not, you can create a new project with Create React App and copy your existing project into it. (Yes, it's a bit of work, but you'll thank me later.)
- Your React app doesn't use BrowserRouter. If it does, switch to HashRouter since it's supported by GitHub. If you absolutely must use BrowserRouter, there's a trick with a 404.html redirection code, but that's a play for another time.
- If you plan to use a custom domain, you need to configure and verify your GitHub server with your DNS. If you haven't done this yet, check out configuring custom domain for your github pages site or wait until it interests me.
- Your React code is pushed to GitHub. If not,
this blog doesn't deserve you, andyou should probably go do that first.
Alright, let's dive in!
Configurations
Step-1 Install gh-pages
:
If you prefer npm: npm install --save gh-pages
If you prefer yarn: yarn add gh-pages
Step-2 Add a deploy script in package.json
:
If you want to host at your GitHub homepage (https://yourusername.github.io), add this script:
"deployToGitHub": "npm run build && gh-pages -b master -d build"
To deploy at https://yourusername.github.io/your-repo-name or custom domain, add this script:
"deployToGitHub": "npm run build && gh-pages -d build"
Step-3 Add the homepage
key-value to the package.json
:
- For a custom domain:
"homepage": "https://yourwebsite.com"
- For GitHub homepage:
"homepage": "https://yourusername.github.io"
- For Github repo page https://yourusername.github.io/your-reponame:
"homepage": "https://yourusername.github.io/your-reponame"
Step-4 Deploy your site to GitHub:
run npm run deployToGitHub
Step-5 Ensure your repo uses GitHub Pages:
Go to your repository settings: your-reponame/settings/pages
Set GitHub Pages to use the gh-pages
branch:
Step-6 Configure the custom domain (If needed):
Add a
CNAME
file with your custom domain url at public folder.
Or configure it in
your-reponame/settings/pages
as below.
I recommend enforcing HTTPS, which gives you a free SSL certificate.
Your website will be up and running at your configured domain within 2-3 minutes!
If you need any help, feel free to reach out to me on LinkedIn, Twitter, or contact form at rpkr.in.
Good luck on your journey! 🌟
Top comments (0)