How to Deploy Astro to GitHub Pages Easily
To deploy an
Astro project to GitHub Pages, build your site using npm run build and then push the generated dist folder to the gh-pages branch. Use the gh-pages npm package or GitHub Actions to automate deployment.Syntax
Deploying Astro to GitHub Pages involves these main steps:
- Build command:
npm run buildgenerates static files in thedistfolder. - Deploy command: Use
gh-pages -d distto pushdistto thegh-pagesbranch. - GitHub Pages settings: Set the source branch to
gh-pagesin your repository settings.
bash
npm run build gh-pages -d dist
Example
This example shows how to set up deployment scripts in package.json and deploy your Astro site to GitHub Pages.
json
{
"scripts": {
"build": "astro build",
"deploy": "gh-pages -d dist"
}
}
# Then run these commands in terminal:
npm install gh-pages --save-dev
npm run build
npm run deployOutput
Publishing to gh-pages branch...
Published successfully.
Common Pitfalls
Common mistakes when deploying Astro to GitHub Pages include:
- Not setting the
baseoption inastro.config.mjsto your repository name, causing broken links. - Forgetting to install
gh-pagesor not adding deploy scripts. - Not selecting the
gh-pagesbranch as the GitHub Pages source in repository settings.
Correct astro.config.mjs base example:
javascript
import { defineConfig } from 'astro/config'; export default defineConfig({ base: '/your-repo-name/', });
Quick Reference
Summary tips for deploying Astro to GitHub Pages:
- Set
baseinastro.config.mjsto your repo name with slashes. - Build your site with
npm run build. - Deploy using
gh-pages -d distor GitHub Actions. - Choose
gh-pagesbranch as GitHub Pages source. - Use
gh-pagesnpm package for easy deployment.
Key Takeaways
Always set the base path in astro.config.mjs to your GitHub repo name for correct URLs.
Use npm scripts with gh-pages package to automate deployment to the gh-pages branch.
Build your Astro site before deploying to generate static files in the dist folder.
Configure GitHub Pages source branch to gh-pages in your repository settings.
Check for common mistakes like missing base config or wrong branch selection.