Vercel has an official example for deploying to GitHub Pages. Look at this as well to make an informed decision on what strategy works best for you.
My original setup for hosting a static Next.js site on GitHub Pages was made using a blog post that unfortunately no longer exists. So here is a guide for what I have now.
Configure Next.js
📢 This guide is using Next.js version 14 using app router.
In your next.config.js
file add the following:
const nextConfig = {
output: 'export',
// Any other config options
};
module.exports = nextConfig;
In your /app/layout.tsx
file add the following at the bottom of the file:
export const dynamic = 'force-static';
Lastly add a blank .nojekyll
file in the /public/
folder to disable GitHub Pages from trying to create a Jekyll website.
Setup GitHub repository
Configure your repo for automating deployments.
Enable GitHub Pages
To enable Pages in your GitHub repo:
- Create and push a gh-pages
- Go to Settings -> Pages
- Set the Build and deployment -> Source to Deploy from a branch
- Set the branch to gh-pages
- Set the folder to / (root)
- Save
Generate deploy keys
For GitHub Actions to commit and push to the gh-pages
branch you need to generate public and private keys for it to authenticate.
In your Next.js root directory run the following command:
ssh-keygen -t rsa -b 4096 -C "$(git config user.email)" -f gh-pages -N ""
Setup deploy key
In your GitHub repo:
- Go to Settings -> Deploy Keys
- Click Add deploy key
- Add title: Public key of ACTIONS_DEPLOY_KEY
- Add key: copy and paste the public key you just generated
- Check: Allow write access
- Add key
Setup private key
In your GitHub repo:
- Go to Settings -> Secrets and variables -> Actions
- Click New repository secret
- Add name: ACTIONS_DEPLOY_KEY
- Add secret: copy and paste the private key you just generated
- Add secret
Now GitHub Actions is able to authenticate with your repo. Delete the two keys from your Next.js root directory. Do not commit or share those files with anyone.
Setup GitHub Actions
Add a workflow file /.github/workflows/deploy.yml
:
name: Deploy to Github Pages
on:
push:
branches:
- main
workflow_dispatch:
jobs:
deployment:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.1.5
- name: Setup Node
uses: actions/setup-node@v4.0.2
with:
node-version: 'lts/*'
cache: 'npm'
- name: Build
run: |
npm i
npm run build
- name: Deploy
uses: peaceiris/actions-gh-pages@v4
with:
deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }}
publish_dir: ./out
Enjoy your site
You're done! Now whenever you push to the main
branch your site will automatically build and deploy and be publicly available at repo-name.github.io
.