0
0
AstroHow-ToBeginner ยท 3 min read

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 build generates static files in the dist folder.
  • Deploy command: Use gh-pages -d dist to push dist to the gh-pages branch.
  • GitHub Pages settings: Set the source branch to gh-pages in 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 deploy
Output
Publishing to gh-pages branch... Published successfully.
โš ๏ธ

Common Pitfalls

Common mistakes when deploying Astro to GitHub Pages include:

  • Not setting the base option in astro.config.mjs to your repository name, causing broken links.
  • Forgetting to install gh-pages or not adding deploy scripts.
  • Not selecting the gh-pages branch 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 base in astro.config.mjs to your repo name with slashes.
  • Build your site with npm run build.
  • Deploy using gh-pages -d dist or GitHub Actions.
  • Choose gh-pages branch as GitHub Pages source.
  • Use gh-pages npm 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.