My nextjs app is statically exported. I have dynamic pages rendered at build time correctly by using getStaticPaths and getStaticProps. They are defined in a file named [exercised].js with a parameter.
I can generate most of the pages like this without any problem. But I want to be able to generate most of my pages statically and still be able to generate new pages on demand with client-side rendering when the page was not statically rendered during the production build.
However, according to the docs, I could either enable or disable fallback for my dynamic pages. But I cannot enable fallback because I am exporting the app statically. If fallback is disabled, I am not able to do any client-side data fetching and page rendering on my own, because the 404 not found response is returned by default for any page not generated during the build.
I wish I could keep statically exporting my pages and still have some way to render them on client-side when they are not available statically.
I am not expecting any incremental SSR, because I don't have a backend server in nextJs, just want to be able to fetch data (from another non NextJs API) every time anyone hits a specific page not pre-rendered. I am also aware that these pages will not be indexed properly by search engines.
Is there any way I can achieve this?
I managed to solve this problem by hacking at the 404 page: 404.tsx/js
This isn't an easy problem to solve elegantly, since by nature a static export is expected to provide all pages by default, and a redirect would really need to be handled by the backend. Most providers would instead redirect to the 404 page provided by Next.JS. We can use this to our advantage and instead render the content we want on the 404 page:
// in your 404.tsx
const NotFound: FC = () => {
const router = useRouter();
const path = router.asPath;
// This will match for dynamic/<id>/path
const match = path.match(/^\/dynamic\/(.+)\/path$/);
// Check to see if current route is your dynamic route...
if (match) {
const id = match[1];
// if so, render your dynamic component
return <YourDynamicComponent id={id}/>;
}
// else render regular 404 page
return <NotFoundPage />
}
While an average user will see the content they want, the static server will still return a 404 code. This will make the page behave differently to web crawlers or bots.