undefined getStaticProps causes build failure on page that doesn't exist

124 views Asked by At

I'm fetching page data from a cms, so far I have only one page in pages/posts.


pages/posts/[slug].js

import { getAllPostsWithSlug, getPostAndMorePosts } from '../../lib/api';

export default function Post({ post }) {
  const router = useRouter();
  const { slug } = router.query;
  return (
    <div>
      <p>
        title: {typeof post == 'undefined' ? 'no post' : post.title}
      </p>
    </div>
  );
}

export async function getStaticProps({ params, preview = null }) {
  const data = await getPostAndMorePosts(params.slug, preview);
  const content = await markdownToHtml(data?.posts[0]?.content || '');

  return {
    props: {
      preview,
      post: {
        ...data?.posts[0],
        content,
      },
      morePosts: data?.morePosts,
    },
  };
}

export async function getStaticPaths() {
  const allPosts = await getAllPostsWithSlug();
  return {
    paths: allPosts?.map((post) => `/posts/${post.slug}`) || [],
    fallback: true,
  };
}

That will correctly display post.title, but if I access the property directly with

<p>title: {post.title}</p>

I get the build error: post undefined

Is next trying to build a page out of the template with no data? When the build succeeds I only have one route in /posts.

0

There are 0 answers