Search code examples
graphqlnext.jsapollo-clientssg

Next js - Can't generate dynamic getStaticPaths with apollo client api


I wan't to generate a list of my posts' slugs for a SSG export in next.js, using Apollo graphql client. Here's my code:

import { gql } from "@apollo/client";
import client from "../../graphql/apollo-client";
import { BLOG_POSTS, POST_DATA } from "../../graphql/apollo-queries";


export async function getStaticPaths() {
   const { loading, error, data } = await client.query({ query: BLOG_POSTS });
   const peths = data.posts.nodes.map((post) => ({
      params: { slug: post.slug },
   }));

   return {
      paths: peths || [],
      fallback: true,
   };
}



export async function getStaticProps({ params }) {
   const { data } = await client.query({
      query: POST_DATA,
      variables: { id: params.slug, idType: "SLUG" },
   });

   return {
      props: {
         post: data.post,
      },
   };
}

export default function BlogSlug({ post }) {
   return (
       <h1>{post.title}</h1>
   )
}

This is working correctly when I use npm run dev which starts the next application in development mode, but when I want run next build && next export, it seems like the API isn't working and data returns undefined, thus, no pages are generated and it throws an error saying TypeError: Cannot read property 'title' of undefined


Solution

  • changing fallback: true to fallback: false solved the problem.

    from Next.js website (https://nextjs.org/docs/messages/prerender-error):

    Make sure your component handles fallback if it is enabled in getStaticPaths.