Spa Github Pages
Host single page apps with GitHub Pages
Install / Use
npx skills add rafgraph/spa-github-pagesInstalls into whichever agent you are using.
README
Single Page Apps for GitHub Pages
[Demo app][demoapp]
This is a lightweight solution for deploying single page apps with [GitHub Pages][ghpagesoverview]. You can easily deploy a [React][react] single page app with [React Router][reactrouter] <BrowserRouter />, like the one in the [demo app][demoapp], or a single page app built with any frontend library or framework.
Why it's necessary
GitHub Pages doesn't natively support single page apps. When there is a fresh page load for a url like example.tld/foo, where /foo is a frontend route, the GitHub Pages server returns 404 because it knows nothing of /foo.
How it works
When the GitHub Pages server gets a request for a path defined with frontend routes, e.g. example.tld/foo, it returns a custom 404.html page. The [custom 404.html page contains a script][404html] that takes the current url and converts the path and query string into just a query string, and then redirects the browser to the new url with only a query string and hash fragment. For example, example.tld/one/two?a=b&c=d#qwe, becomes example.tld/?/one/two&a=b~and~c=d#qwe.
The GitHub Pages server receives the new request, e.g. example.tld/?/..., ignores the query string and returns the index.html file, which has a [script that checks for a redirect in the query string][indexhtmlscript] before the single page app is loaded. If a redirect is present it is converted back into the correct url and added to the browser's history with window.history.replaceState(...), but the browser won't attempt to load the new url. When the [single page app is loaded][indexhtmlspa] further down in the index.html file, the correct url will be waiting in the browser's history for the single page app to route accordingly. (Note that these redirects are only needed with fresh page loads, and not when navigating within the single page app once it's loaded).
Usage instructions
For general information on using GitHub Pages please see [Getting Started with GitHub Pages][ghpagesbasics], note that pages can be [User, Organization or Project Pages][ghpagestypes]
Basic instructions - there are two things you need from this repo for your single page app to run on GitHub Pages.
- Copy over the [
404.html][404html] file to your repo as is- Note that if you are setting up a Project Pages site and not using a [custom domain][customdomain] (i.e. your site's address is
username.github.io/repo-name), then you need to set [pathSegmentsToKeepto1in the404.htmlfile][pathsegmentstokeep] in order to keep/repo-namein the path after the redirect. If you are using React Router you'll need to tell it to use therepo-nameas thebasename, for example<BrowserRouter basename="/repo-name" />.
- Note that if you are setting up a Project Pages site and not using a [custom domain][customdomain] (i.e. your site's address is
- Copy the [redirect script][indexhtmlscript] in the
index.htmlfile and add it to yourindex.htmlfile - Note that the redirect script must be placed before your single page app script in yourindex.htmlfile.
Detailed instructions - using this repo as a boilerplate for a React single page app hosted with GitHub Pages. Note that this boilerplate is written in TypeScript but is setup to accept JavaScript files as well. It was previously written in JS and if you prefer a JS only boilerplate you can use [version 6][spa-github-pages-v6].
- Clone this repo (
$ git clone https://github.com/rafgraph/spa-github-pages.git) - Delete the
.gitdirectory (cdinto thespa-github-pagesdirectory and run$ rm -rf .git) - Instantiate the repository
- If you're using this boilerplate as a new repository
$ git initin thespa-github-pagesdirectory, and then$ git add .and$ git commit -m "Add SPA for GitHub Pages boilerplate"to initialize a fresh repository- If this will be a Project Pages site, then change the branch name from
maintogh-pages($ git branch -m gh-pages), if this will be a User or Organization Pages site, then leave the branch name asmain - Create an empty repo on GitHub.com (don't add a readme, gitignore or license), and add it as a remote to the local repo (
$ git remote add origin <your-new-github-repo-url>) - Feel free to rename the local
spa-github-pagesdirectory to anything you want (e.g.your-project-name)
- If you're adding this boilerplate as the
gh-pagesbranch of an existing repository- Create and checkout a new orphaned branch named
gh-pagesfor your existing repo ($ git checkout --orphan gh-pages), note that thegh-pagesbranch won't appear in the list of branches until you make your first commit - Delete all of the files and directories (except the
.gitdirectory) from the directory of your existing repo ($ git rm -rf .) - Copy all of the files and directories (including hidden dot files) from the cloned
spa-github-pagesdirectory into your project's now empty directory ($ mv path/to/spa-github-pages/{.[!.],}* path/to/your-projects-directory) $ git add .and$ git commit -m "Add SPA for GitHub Pages boilerplate"to instantiate thegh-pagesbranch
- Create and checkout a new orphaned branch named
- If you're using this boilerplate as a new repository
- Set up a custom domain (optional) - see GitHub Pages instructions for [setting up a custom domain][customdomain]
- Update the [
CNAMEfile][cnamefile] with your custom domain, don't includehttps://, but do include a subdomain if desired, e.g.wwworyour-subdomain - Update your
CNAMEand/orArecord with your DNS provider - Run
$ dig your-subdomain.your-domain.tldto make sure it's set up properly with your DNS (don't includehttps://)
- Update the [
- Set up without using a custom domain (optional)
- Delete the [
CNAMEfile][cnamefile] - If you are creating a User or Organization Pages site, then that's all you need to do
- If you are creating a Project Pages site, (i.e. your site's address is
username.github.io/repo-name):- Set [
pathSegmentsToKeepto1in the404.htmlfile][pathsegmentstokeep] in order to keep/repo-namein the path after the redirect - Add your
repo-nameto the absolute path of assets inindex.html, change the [bundle.js src][indexhtmlspa] to"/repo-name/build/bundle.js" - In React Router set the
basenameto/repo-name[here][browserrouter] like<BrowserRouter basename="/repo-name" /> - In the [start script][startscript] in
package.jsonreplace--openwith--open-page repo-name - In
webpack.config.js:- Add
repo-nameto the [publicPath][webpackpublicpath] likepublicPath: '/repo-name/build/' - Change the [
historyApiFallback rewrites][webpackdevrewrites] torewrites: [{ from: /\/repo-name\/[^?]/, to: '/404.html' }]
- Add
- Set [
- Delete the [
- Run
$ npm installto install React and other dependencies, and then run$ npm run buildto update the build $ git add .and$ git commit -m "Update boilerplate for use with my domain"and then push to GitHub ($ git push origin gh-pagesfor Project Pages or$ git push origin mainfor User or Organization Pages) - the example site should now be live on your domain- Create your own site
- Write your own React components, create your own routes, and add your own style
- Note that the example site is styled with [Stitches][stitches] and uses [React Interactive][reactinteractive] for the links and other interactive components.
- Change the [title in
index.html][indexhtmltitle] and the [title in404.html][404htmltitle] to your site's title - Remove the [favicon links][favicon] from the header of
index.htmland the [favicondirectory][favicondir]. - Update or delete [
robots.txt][robots] and [sitemap.txt][sitemap] as you see fit (see SEO section below for more info) - Change the readme, license and package.json as you see fit
- For testing changes locally see development environment info below
- To publish your changes to GitHub Pages run
$ npm run build(this runswebpack -pfor [production][webpackproduction]) to update the build, then$ git commitand$ git pushto make your changes live
- Write your own React components, create your own routes, and add your own style
Serving from the /docs folder on the main branch - alternatively you can serve your site from the /docs folder instead of the root folder while your source code remains in the root folder.
- After following the previous set of instructions for using this repo as a boilerplate, create a
/docsfolder in the root and moveindex.html,404.htmland the/buildfolder into/docs - Add
--content-base docs/to the [start script][startscript] inpackage.json - In
webpack.config.jschange the [output path][webpackoutputpath] topath: `${__dirname}/docs/build`, - On GitHub in your repo settings select the
/docsfolder as the source for GitHub Pages
Development environment
I have included webpack-dev-server for testing changes locally. It can be accessed by running $ npm start (details below). Note that webpack-dev-server automatically creates a new bundle whenever the source files change and serves the bundle from memory, so you'll never see the bundle as a file saved to disk.
$ npm startruns the [start script][startscript] inpackage.json, which runs the command$ webpack-dev-server --host 0.0.0.0 --disable-host-check --open--host 0.0.0.0 --disable-host-checkis so you can access the site on your local network from other devices athttp://[YOUR COMPUTER'S IP ADDRESS]:8080--openwill open automatically open the site in your browser
webpack-dev-serverwill serveindex.htmlathttp://localhost:8080(port8080is the default). Note that you must load theindex.htmlfrom the server and not just open it directly in the browser or the scripts won't load.
SEO
When I first created this solution in 2016 Google treated the redirect in 404.html the same as a 301 redirect and indexed pages without issue. Around 2019 Google changed their algorithm and no longer follows redirects in 404.html. In order to have all the pages on your site in
Related Skills
node-connect
385.5kDiagnose OpenClaw Android, iOS, or macOS node pairing, QR/setup code, route, auth, and connection failures.
blender-python-addon
40.5kBlender Python add-on rules for operators, panels, properties, registration, testing, and API-safe scripting
flutter-development-guidelines-cursorrules-prompt-file
40.5kCursor rules for Flutter development with MVVM architecture, Riverpod state management, Material widgets, and Dart style guidelines.
commit-push-pr
140.7kCommit, push, and open a PR
