I’m writing my web app in Next.js and I’m hosting it on Github Pages (an outside constraint, would personally use Vercel or something else).
I have a dynamic route: webapp.com/experiments/[id]
.
ID needs to be dynamically generated whenever a users creates an experiment, therefore I cannot preload all the IDs to build the static pages.
It is important these pages are able to be generated dynamically without needing to re-build / re-deploy the project.
On localhost
, I’m able to go to my page and it is able to retrieve data and display it on the page.
However, once I’ve hosted it onto Github Pages, I can click to the page and it will load, but when I try to go directly to the URL, it gives me a 404.
I’ve set up getStaticPaths
and getStaticProps
and it built out the known pages but when I go to a URL for a new experiment it still gives me a 404.
What am I missing?
Is there a different way of doing this?
export async function getStaticPaths() {
// Fetch initial list of experiment IDs from your database
const experimentIds = await fetchExperimentUrls();
// Generate paths for static generation
const paths =
experimentIds.urls.map((url: string) => ({
params: { url: url.toString() },
}));
return {
paths,
fallback: true,
};
}
export async function getStaticProps({ params }: any) {
const { url } = params;
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/experiments/${url}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
);
const experimentProps = await res.json();
return {
props: {
experimentProps,
},
revalidate: 60, // Optional: Set a revalidation time (in seconds) to update the static page
};
}
2
Answers
I missed an important part of your question when I commented. You’re dynamically rendering some pages, but you’re deploying static assets. Github Pages doesn’t run the Next server, it assumes you’re deploying static pages (all of them, already built). There’s no way for a site hosted on gh-pages to dynamically fetch data server-side, because there’s no server. If fetching new experiments is a requirement, you’ll need to host your app on a VPS or cloud provider.