Blog>
Snippets

Fallback Pages for Dynamic Routes

Utilize the getStaticPaths fallback option to serve a fallback page while static pages for dynamic routes are being generated.
import { useRouter } from 'next/router';

export default function Page({ data }) {
  const router = useRouter();
  
  // Check if the page is still loading
  if (router.isFallback) {
    // You can render a loading spinner or a placeholder here
    return <div>Loading...</div>;
  }

  // Once the page has loaded, render the page with data
  return <div>{data.title}</div>;
}
This snippet is for a page component in Next.js. It uses the useRouter hook from Next.js to detect if the current page is a fallback page. If the page is still generating (isFallback is true), it renders a loading message. Once the generation is completed, it renders the actual page content.
export async function getStaticPaths() {
  return {
    // Define the paths you want to pre-render
    paths: [
      { params: { id: '1' } },
      { params: { id: '2' } },
      // etc.
    ],
    // Enable fallback mode to generate pages on-demand
    // after the initial build
    fallback: true,
  };
}
This snippet demonstrates the getStaticPaths function in Next.js used for dynamic routes. The function defines a list of paths to generate at build time. By setting fallback to true, it enables on-demand generation of pages for paths not defined in the list. During this generation, the router will use the isFallback state to serve a fallback page.