DEV Community

Cover image for Host React app in GitHub pages
Vishnu Prasaath
Vishnu Prasaath

Posted on • Originally published at blog.vishnuprasaath.dev on

Host React app in GitHub pages

There is a lot of documentation out there to host your react app on GitHub pages for FREE, which is accessible via https://<git_user>.github.io/<repo_name>

ex: adam.github.io/portfolio , vishnu.github.io/my-dev

But this doc will guide you to host react app at https://<git_user>.github.io (no need to cling the repo name with URL)

ex: adam.github.io , vishnu.github.io

This approach is preferred for hosting a portfolio or dev-profile website.

There are three types of GitHub Pages sites:

  1. User Site

  2. Project Site

  3. Organization Site

This blog is inclined toward setting up a User Site

Let's get started!

Step 1 - Create a repo on GitHub

Create a new GitHub repo named username.github.io (replace username with your current git user name) and make it Public (to host private repo in GH pages you need a GitHub Enterprise account)

img1


Step 2 - Create React app and Push to repo

Create your react app following the official doc - https://create-react-app.dev/docs/getting-started/

Init git and push it to the above-created repo

git init
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/username/username.github.io.git
git push -u origin main

Enter fullscreen mode Exit fullscreen mode

Step 3 - Setup gh-pages

The npm package gh-pages helps in configuring and deploying your app to GitHub pages

npm install gh-pages save-dev

Enter fullscreen mode Exit fullscreen mode

Homepage property

Add the below homepage property to your package.json file.

For free GitHub user site, add this: 
"homepage": "https://{username}.github.io"

If you own a domain, add this:
"homepage": "https://mydomainname.com"

Enter fullscreen mode Exit fullscreen mode

img2

Deploy Script

Add both predeploy and deploy property scripts to the package.json as below

"predeploy": "npm run build",
"deploy": "gh-pages -d build"

Enter fullscreen mode Exit fullscreen mode

predeploy - bundle the react application

deploy - deploy the bundled file.

img3

Push these changes to the git repo

git commit -m "configure gh-pages"
git push

Enter fullscreen mode Exit fullscreen mode

Step 4 - Deploy the app to GitHub Pages

Run the below command to deploy your react application to GitHub Pages

npm run deploy

Enter fullscreen mode Exit fullscreen mode

Step 5 - Finally access the deployed site

  • Go to the GitHub repo

  • Click Settings menu

  • Go to the Code and Automation -> Pages section

  • In the Build and Deployment section, select Source to Deploy from a branch

  • Select the branch to "gh-pages" and click on the "Save" button

Visit username.github.io and check out your site.

Yayy!

Your website is hosted for FREEEE in GitHub Pages and accessible to the world.

Top comments (0)