CI/CD and automation · Beginner · 22 min
Deploy a static site to GitHub Pages with GitHub Actions
By Padding · Updated 18 Nov 2026
Node.js 26.13.1 · Vite 8.3.8 · GitHub Actions · actionlint 1.7.12 · checked in the node:26 image
You will have a small Vite site that GitHub Actions builds and publishes to GitHub Pages on every push to main, first at its project-site path and then on your own domain over HTTPS, with deploys that queue instead of colliding.
On this page
GitHub Pages serves static files from GitHub's own hosting at an address like https://<user>.github.io/<repo>/. For years the usual way in was to commit built files to a gh-pages branch. The better way today is to let a GitHub Actions workflow build the site and hand the result straight to Pages, so the repository holds only source code and every deploy is tied to the commit and the workflow run that produced it.
In this tutorial you build that pipeline for a one-page site: the Ibadan Book Swap, a fictional monthly meet-up where people trade books. You make the site with Vite, prove locally that it works when it is served from a sub-folder, write a workflow with a build job and a deploy job, publish it, move it to your own domain over HTTPS, and stop overlapping deploys from tripping over each other. A small Playwright script checks the rendered page in a real browser, first on your machine and then against the live site.
Know the limits before you start. GitHub Pages works in public repositories on GitHub Free, and in private ones on paid plans. A published site can be at most 1 GB, a deploy that takes longer than 10 minutes times out, and there is a soft bandwidth limit of 100 GB per month. GitHub's terms rule out using Pages as free hosting for an online shop or a software-as-a-service product. A club page, a portfolio, documentation or a project site is well within what it is for.
All commands run in a terminal on macOS or Linux.
Step 1 · Build the book swap site with Vite
Create a throwaway folder and a package.json by hand, so you know every line in it. Then install Vite as a development dependency, pinned to an exact version:
mkdir -p ~/book-swap-demo
cd ~/book-swap-demo
cat > package.json <<'JSON'
{
"name": "book-swap",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}
JSON
npm install --save-dev --save-exact vite@8.3.8
npx vite --versionVite treats index.html at the top of the project as the entry point and follows its script tag into src/. Files in public/ are copied into the build unchanged. Create the page, a stylesheet, a list of meet-ups, the script that renders them, and a small logo:
mkdir -p src public
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="/logo.svg" type="image/svg+xml">
<title>Ibadan Book Swap</title>
</head>
<body>
<header id="masthead">
<h1>Ibadan Book Swap</h1>
</header>
<main>
<p>Bring a book, take a book. We meet on the first Sunday of every month.</p>
<h2>Next meet-ups</h2>
<ul id="meetups"></ul>
</main>
<script type="module" src="/src/main.js"></script>
</body>
</html>
HTML
cat > src/style.css <<'CSS'
body {
margin: 0 auto;
max-width: 36rem;
padding: 1.5rem 1rem;
font-family: system-ui, sans-serif;
line-height: 1.5;
background: #f6f1e7;
color: #1f1d1a;
}
#masthead { display: flex; align-items: center; gap: 0.75rem; }
#meetups li { margin-bottom: 0.5rem; }
CSS
cat > src/meetups.js <<'JS'
export const meetups = [
{ date: '6 December 2026', place: 'Community hall, Bodija', theme: 'Short stories' },
{ date: '3 January 2027', place: 'Community hall, Bodija', theme: 'Poetry in Yoruba and English' },
{ date: '7 February 2027', place: 'Reading room, Mokola', theme: 'Books you lent and never got back' },
]
JS
cat > src/main.js <<'JS'
import './style.css'
import { meetups } from './meetups.js'
// BASE_URL is the path the site is served from, such as "/" or "/book-swap/".
const logo = document.createElement('img')
logo.className = 'logo'
logo.src = `${import.meta.env.BASE_URL}logo.svg`
logo.alt = ''
logo.width = 48
logo.height = 48
document.querySelector('#masthead').prepend(logo)
const list = document.querySelector('#meetups')
for (const meetup of meetups) {
const item = document.createElement('li')
item.textContent = `${meetup.date} · ${meetup.place} · ${meetup.theme}`
list.append(item)
}
JS
cat > public/logo.svg <<'SVG'
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48">
<rect width="48" height="48" rx="8" fill="#1f1d1a"/>
<path d="M10 14h12v22H10zM26 14h12v22H26z" fill="#f6f1e7"/>
</svg>
SVG
npm run buildNote how the logo's address is built in main.js. A plain '/logo.svg' string would work on your machine and break on GitHub, because a project site does not live at the root of its domain. import.meta.env.BASE_URL is replaced at build time with the path the site is served from, which you set in the next step.
Check it worked
ls dist dist/assets
du -sh distdist holds index.html, logo.svg and an assets folder with one JavaScript and one CSS file, each with a hash in its name. The whole site is a few kilobytes. That matters for visitors on prepaid mobile data, which is how a lot of people in Nigeria and elsewhere browse: keep an eye on this number as the site grows, and compress images before you add them.
Step 2 · Serve the build from a project-site path
Your repository will be called book-swap, so GitHub Pages will serve the site from https://<user>.github.io/book-swap/. Vite's base option tells the build which path that is. Rather than hard-code it, read it from an environment variable, because the workflow will supply the right value and the value changes when you add a custom domain later:
cat > vite.config.js <<'JS'
import { defineConfig } from 'vite'
// The workflow sets BASE_PATH; without it the site is built for the root of a domain.
export default defineConfig({
base: process.env.BASE_PATH || '/',
})
JS
BASE_PATH=/book-swap/ npm run build
grep -o '"/book-swap/[^"]*"' dist/index.htmlThe grep prints three lines: the favicon, the script and the stylesheet, each starting with /book-swap/. Vite rewrote the absolute paths in index.html for you. It does not rewrite strings in your JavaScript, which is why main.js uses BASE_URL.
Now serve the build the way Pages will. In a second terminal, in ~/book-swap-demo, start Vite's preview server with the same base path. It keeps running until you press Ctrl+C:
BASE_PATH=/book-swap/ npm run preview -- --port 4173 --strictPortLooking at the page by eye catches some problems, but not a missing stylesheet on a slow connection or a logo that quietly fails. Install Playwright and a copy of Chromium in the project, and write a script that loads a page and checks what a visitor gets. On Linux, --with-deps installs the system libraries Chromium needs and may ask for your password:
npm install --save-dev --save-exact playwright@1.65.1
npx playwright install --with-deps chromium
cat > check-site.mjs <<'JS'
import { chromium } from 'playwright'
import assert from 'node:assert/strict'
const site = process.argv[2]
if (!site) throw new Error('Usage: node check-site.mjs <url>')
const browser = await chromium.launch()
try {
const page = await browser.newPage()
// Record every request that fails, including the favicon and the logo.
const failed = []
page.on('response', (r) => { if (r.status() >= 400) failed.push(`${r.status()} ${r.url()}`) })
await page.goto(site, { waitUntil: 'networkidle' })
await page.getByRole('heading', { level: 1, name: 'Ibadan Book Swap' }).waitFor()
assert.equal(await page.locator('#meetups li').count(), 3, 'three meet-ups are listed')
const background = await page.evaluate(() => getComputedStyle(document.body).backgroundColor)
assert.equal(background, 'rgb(246, 241, 231)', 'the stylesheet is applied')
const logo = page.locator('img.logo')
assert.ok(await logo.evaluate((img) => img.complete && img.naturalWidth > 0), 'the logo loaded')
assert.deepEqual(failed, [], 'no request failed')
console.log(`OK: ${site} shows 3 meet-ups, its stylesheet and its logo`)
} finally {
await browser.close()
}
JSThe script takes the address as an argument, so you can run it against your machine now and against the live site later.
Check it worked
node check-site.mjs http://localhost:4173/book-swap/It prints OK: http://localhost:4173/book-swap/ shows 3 meet-ups, its stylesheet and its logo. If you open http://localhost:4173/book-swap/ in your browser you see the heading, the logo and three meet-ups on a cream background. Stop the preview server with Ctrl+C before you go on.
Step 3 · Push the source and choose GitHub Actions as the Pages source
Keep node_modules and the build output out of Git. The workflow rebuilds dist from source on every run, so committing it would only cause conflicts:
cat > .gitignore <<'TXT'
node_modules/
dist/
TXT
git init -b main
git add .
git commit -m "Add the book swap site"
git ls-filesgit ls-files lists the source files, package.json, package-lock.json, vite.config.js, check-site.mjs and .gitignore, with nothing from dist or node_modules. Commit the lock file: the workflow installs from it, so GitHub builds with the same Vite you used.
On GitHub, create a new public repository named book-swap with no README, licence or .gitignore, so it is empty. Then point your local repository at it and push. Replace YOUR-USER with your GitHub username:
git remote add origin git@github.com:YOUR-USER/book-swap.git
git push -u origin mainNow tell Pages where its files come from. In the repository, open Settings, then Pages. Under Build and deployment, set Source to GitHub Actions. GitHub offers some workflow templates at this point; ignore them, because you write your own next.
Check it worked
The repository's file list on GitHub shows your source files and no dist folder. The Pages settings show GitHub Actions as the source, and no site is live yet.
Step 4 · Write the Pages workflow
The workflow has two jobs. build installs, builds and packages dist as a Pages artifact. deploy takes that artifact and publishes it. Splitting them keeps the permission to publish away from the job that runs npm ci and your build scripts.
mkdir -p .github/workflows
cat > .github/workflows/pages.yml <<'YAML'
name: Pages
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
pages: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: 26
cache: npm
- name: Read the Pages settings
id: pages
uses: actions/configure-pages@v6
- run: npm ci
- name: Build for the Pages path
run: npm run build
env:
BASE_PATH: ${{ steps.pages.outputs.base_path }}/
- uses: actions/upload-pages-artifact@v5
with:
path: dist
deploy:
needs: build
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Publish the artifact
id: deployment
uses: actions/deploy-pages@v5
YAML
actionlint
echo "actionlint exit code: $?"The parts that matter:
configure-pagesreads your repository's Pages settings. Itsbase_pathoutput is/book-swapfor a project site and an empty string once a custom domain is set. The build step adds a slash and passes it to Vite asBASE_PATH, so the same workflow builds/book-swap/today and/after the domain step, with no edit.upload-pages-artifactpacksdistinto the archive format Pages expects. It leaves out files and folders whose names start with a dot unless you setinclude-hidden-files: true, which matters if you ever add a.well-knownfolder.deployneedspages: writeto publish andid-token: writesodeploy-pagescan request a short-lived OIDC token that proves which workflow run the artifact came from. No secret or personal token is involved.environment: github-pagesrecords each deploy as a deployment of that environment, with the live address as itsurl. GitHub created the environment when you chose GitHub Actions as the source.
Before you push, run the two commands the build job runs, with the value configure-pages will give it for this repository:
npm ci
BASE_PATH=/book-swap/ npm run build
git add .github/workflows/pages.yml
git commit -m "Build and deploy to GitHub Pages"
git log --onelineCheck it worked
actionlint prints nothing and exits with 0. npm ci installs from the lock file without changing it, the build finishes with the same three /book-swap/ paths as before, and git log --oneline shows two commits.
Step 5 · Push and watch the first deploy
Push the workflow:
git pushOpen the Actions tab. A run of Pages starts with build, then deploy. When deploy finishes, the run's summary shows the site's address under the deploy job, and Settings, Pages says the site is live. The first deploy can take a minute or two longer than later ones.
If configure-pages fails with an error about the Pages site not being found, the source is not set to GitHub Actions yet; set it as in the previous step and re-run the workflow from the run's page.
Check it worked
From ~/book-swap-demo, run the browser check against the live address. Replace YOUR-USER with your username:
node check-site.mjs https://YOUR-USER.github.io/book-swap/It prints the same OK: line as on your machine. A failure that lists 404 responses for /assets/... usually means the site was built with the wrong base path; check the Build for the Pages path step's log for the value of BASE_PATH.
Step 6 · Add a custom domain and turn on HTTPS
This step is optional and needs a domain you control. The example uses www.example.com; replace it with your own subdomain.
First, verify the domain for your account. Verification stops someone else from pointing a site in their account at your domain if your Pages setup ever lapses. Open your profile's Settings (not the repository's), choose Pages, click Add a domain, type www.example.com and continue. GitHub then shows a TXT record to create: a name of the form _github-pages-challenge-YOUR-USER.www.example.com and a value that is a random code. Leave that page open.
At your DNS provider, add two records. The first proves you own the domain; the second sends visitors to Pages:
- Type
TXT, the name GitHub showed you, and the code as the value. Many DNS providers add the domain for you, so the name you type there is_github-pages-challenge-YOUR-USER.www. - Type
CNAME, namewww, valueYOUR-USER.github.io. Point it at your user domain only, without/book-swap.
For a bare domain such as example.com, GitHub's custom domain documentation lists A and AAAA records in place of the CNAME; the TXT record is still needed. Once the records are in place, check them:
dig TXT _github-pages-challenge-YOUR-USER.www.example.com +short
dig www.example.com +noall +answerThe first command prints the code in quotes. The second shows www.example.com as a CNAME for YOUR-USER.github.io, followed by addresses. DNS changes can take a while to spread, so give it time if a record is missing. When the TXT record shows up, go back to the page GitHub left open and click Verify. Your profile's Pages settings then list www.example.com as verified. Keep the TXT record in place afterwards; removing it can undo the verification.
Then, in the repository's Settings, Pages, type www.example.com under Custom domain and save. You do not need a CNAME file in the repository: when Pages publishes from an Actions workflow it does not create one and ignores any that exists.
With a custom domain, configure-pages reports an empty base_path, so the site has to be built for / again. Your workflow already handles that. Start a fresh run from Actions, Pages, Run workflow, because the deployed files still point at /book-swap/. Before it finishes, build the same way locally and check the result at the root of a second preview server:
BASE_PATH=/ npm run build
grep -o '"/[^"]*"' dist/index.htmlgrep now prints /logo.svg, /assets/index-....js and /assets/index-....css, with no /book-swap/ prefix. In your second terminal, serve it:
npm run preview -- --port 4174 --strictPortnode check-site.mjs http://localhost:4174/It prints the OK: line for http://localhost:4174/. Stop the preview server with Ctrl+C.
When the DNS check in the Pages settings passes, GitHub requests a certificate from Let's Encrypt for your domain. That can take some minutes; if it is still pending well after that, remove the domain, type it again and save to restart it. When the certificate is ready, tick Enforce HTTPS so plain HTTP requests are redirected.
Check it worked
curl -sI http://www.example.com/ | grep -iE '^(HTTP|location)'
node check-site.mjs https://www.example.com/curl prints two lines: a status line with 301, and a Location: header starting https://www.example.com/. The browser check prints its OK: line for the HTTPS address. The Pages settings show a tick next to your custom domain.
Step 7 · Build pull requests and keep deploys in order
Two gaps remain. Pull requests are never built, so a broken build is only found after a merge. And if two pushes land close together, two deploys can run at once, and the older commit could finish last.
Rewrite the workflow so that pull requests run build only, and deploy runs one at a time. The concurrency group sits on the deploy job rather than the whole workflow, so pull request builds never wait behind a deploy:
cat > .github/workflows/pages.yml <<'YAML'
name: Pages
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
pages: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: 26
cache: npm
- name: Read the Pages settings
id: pages
uses: actions/configure-pages@v6
- run: npm ci
- name: Build for the Pages path
run: npm run build
env:
BASE_PATH: ${{ steps.pages.outputs.base_path }}/
- uses: actions/upload-pages-artifact@v5
with:
path: dist
deploy:
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
needs: build
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
concurrency:
group: pages-deploy
cancel-in-progress: false
steps:
- name: Publish the artifact
id: deployment
uses: actions/deploy-pages@v5
YAML
actionlint
echo "actionlint exit code: $?"How the group behaves: while one deploy runs, the next waits as pending. cancel-in-progress: false means the running deploy is never stopped halfway. If a third push arrives while one is pending, the pending one is cancelled and the newest takes its place, which is what you want: the site ends on the latest commit without publishing every commit in between.
The if on deploy also covers a manual run started from another branch. For a second layer, open Settings, Environments, github-pages and check that its deployment branches are limited to main; GitHub recommends that rule, so add it if it is missing.
Commit the change:
git add .github/workflows/pages.yml
git commit -m "Build pull requests and queue Pages deploys"
git log --onelinegit pushCheck it worked
actionlint exits with 0 and git log --oneline lists three commits. On GitHub, open a pull request that changes a meet-up in src/meetups.js: its checks show build passing and deploy skipped. Merge two small pull requests one after the other, and the second run's deploy job shows as waiting until the first has finished, rather than as cancelled.
Step 8 · Unpublish and tidy up
Skip this step if you are keeping the site.
To take the site offline, open Settings, Pages, click the menu next to Your site is live at and choose Unpublish site. That removes the current deployment but keeps the repository and its settings; any successful workflow run publishes it again, so also disable the Pages workflow under Actions if you want it to stay down. If you added a custom domain, remove it from the Pages settings and delete the CNAME record at your DNS provider (the verification TXT record can stay, so the domain remains protected), so the name does not point at an empty site. Delete the repository under Settings, General if you no longer want it.
On your machine, remove the copy of Chromium that Playwright downloaded, then the project folder:
cd ~/book-swap-demo
npx playwright uninstall
cd ~
rm -rf ~/book-swap-demoCheck it worked
ls ~/book-swap-demo reports that there is no such file or directory. After unpublishing, your github.io address returns a 404 page.
Next steps
- If you have not written a workflow before, the basics of triggers, jobs and actionlint are in /tutorials/github-actions-first-workflow
- Put a manual approval in front of the
github-pagesenvironment: /tutorials/require-approval-before-production-deploys-with-github-environments - Pin actions to commit hashes and tighten permissions further: /tutorials/harden-github-actions-workflows
- Compare with another static host that deploys from the command line: /tutorials/host-a-static-site-on-cloudflare-pages
Related tutorials
- Run only the CI jobs a change needs with path filters and concurrencyYou will have GitHub Actions workflows that skip tests for documentation-only changes without blocking merges, cancel superseded pull request runs, queue deploys instead of cancelling them, and stop any job that runs too long.
- Run Python tests and linters in GitHub Actions with uvYou will have a GitHub Actions workflow that installs a Python project with uv from its lock file, fails on a stale uv.lock, runs Ruff and pytest with a coverage floor on two Python versions, caches uv's downloads and keeps the coverage report as an artifact.
- Publish an npm package from GitHub Actions with trusted publishing and provenanceYou will have a small npm package that GitHub Actions publishes on each version tag through npm trusted publishing, with no NPM_TOKEN secret and a provenance attestation on every release.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials