How to deploy your static Nextjs site to Github Pages for free.
Requirements
Nextjs
Make sure you have Nextjs project that will work as a static export (as Github Pages do not support anything else).
Read the Nextjs unsupported features for a full list of what functionality is unavailable with a statically exported site.
Github
I find it useful to create an organisation so that it's easy to have a root domain setup for when you add a custom domain.
So, for example, you can create an organisation called example-project.
Then, if you name the repository correctly, ie example-project.github.io
Navigating to example-project.github.io will show your project.
This is handy for avoiding path issues later, otherwise you need to change configuration when you switch to a custom domain.
Add the relevant npm packages
npm install gh-pages --devnpm install gh-pages --devAdd the extra script to package.json
"deploy": "next build && gh-pages -d out --nojekyll""deploy": "next build && gh-pages -d out --nojekyll"What this does is builds the project to the out directory and adds the .nojekyll file.
That is required because otherwise Github Pages will assume it is a Jekyll project.
Update next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "export",
trailingSlash: true,
images: {
unoptimized: true,
},
};
export default nextConfig;import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "export",
trailingSlash: true,
images: {
unoptimized: true,
},
};
export default nextConfig;Finally, add some parameters to the Next config.
See https://nextjs.org/docs/app/guides/static-exports for more details on why.
Note: you can use a custom image loader if you need to optimize images.
Deploying
Once everything is setup running
npm run deploynpm run deployShould build the project to the out directory and push it to the gh-pages branch of your repository.
After that, the Github Pages should kick in and start a process to deploy it to the github.io URL you have chosen.