git clone https://github.com/RevanSP/NEXTJS-GHPAGES-EXAMPLE.git
cd NEXTJS-GHPAGES-EXAMPLE
npm install
basePath
FOR STATIC ASSETSImportant: Every time you want to import or reference a file from the public/
folder, you must add basePath
in front of the file path. This ensures your assets are always accessible, both locally and on GitHub Pages.
To ensure your static assets work correctly on GitHub Pages, use the basePath
from useRouter()
in your components:
import { useRouter } from "next/router";
export default function MyComponent() {
const { basePath } = useRouter();
return (
<img src={
basePath + "/my-image.svg"
} alt="My Image" />
);
}
This will automatically prefix your asset paths with the correct base path when deployed to GitHub Pages.
To fetch data from any public API (for example, JSONPlaceholder), you can use getStaticProps
for Static Site Generation (SSG). This will fetch the data at build time and generate static HTML.
// pages/example.js
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await res.json();
return {
props: {
post: data,
},
};
}
export default function Example({ post }) {
return (
<div>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
);
}
Note: The data will be fetched at build time, so it will not update until you rebuild your site.
Tip: Although true ISR (revalidate
in getStaticProps
) is not supported on GitHub Pages, you can mimic ISR by triggering a rebuild of your site using GitHub Actions workflows (for example, on a schedule or via webhook). This way, your static data can be refreshed periodically, even though your code still uses SSG (getStaticProps
).
Workflow Note: The provided GitHub Actions workflow already includes a commented-out schedule
block. To enable automatic periodic rebuilds (like ISR), simply uncomment the schedule
section in .github/workflows/gh-pages.yml
.
# To enable automatic rebuilds (like ISR), uncomment the schedule block below:
# schedule:
# - cron: '*/30 * * * *' # Every 30 minutes
'*/30 * * * *'
means every 30 minutes.minute hour day-of-month month day-of-week
'0 * * * *'
= every hour on the hour.'0 0 * * *'
= every day at midnight..github/workflows/gh-pages.yml
workflow file exists in your repository (see this repo for an example).main
branch.https://<your-github-username>.github.io/<your-repo-name>/
pages/api
or app/api
endpoints. All API logic must be handled externally.getServerSideProps
is not supported. Only static generation is allowed.revalidate
and on-demand static regeneration are not available.fallback: true
or blocking
in getStaticPaths
are not supported. Only fallback: false
works.unoptimized
for images.GitHub Pages only supports static HTML, CSS, and JS. Make sure your Next.js project uses Static Export (output: 'export'
) and does not rely on server-side features.