Home > Blockchain >  How to render dynamic route when a new blog post is added in nextjs without running npm run build co
How to render dynamic route when a new blog post is added in nextjs without running npm run build co

Time:05-03

I have developed a blog app in nextjs, while adding new blog in the database, it does not render the page with new route, instead I have to manually do npm run build to pre-render new blog. Until then it keeps showing not found error.

export async function getStaticPaths() {
  const posts = await service.getAllPosts();
  const paths = posts.map((post) => ({
    params: { slug: post.slug },
  }));
  return { paths, fallback: 'blocking' };
}

export async function getStaticProps({
  params,
}: GetStaticPropsContext<{ slug: string }>) {
  const slug = params?.slug as string;

  try {
    const { post } =
      await service.getPost(slug);
    return {
      props: { post },
      revalidate: 10,
    };
  } catch (error) {
    return { props: { post: {}, error: error.message} };
  }
}

const Blog = ({ post }: Props) => {

return <div>
<p>{post.title}
</div>

}

I am not sure what I am doing wrong here.

When I add a new blog post, I does not render on the client side when i visit: https://example.com/blog/new-slug

CodePudding user response:

This happens because you are using getStaticProps, which only gets called when the website is built. It is useful for pages that don't change very often.

If you want the website to update any time you post something, you should be using getServerSideProps that gets called each time you are visiting the page.

Alternatively you could also do client side fetching, if you don't mind about the SEO.

Another way if you want to keep the performance of a static page, is to use the revalidate option in the getStaticProps. It tells the page to rebuild after a time interval.

  • Related