javascriptreactjsnext.jspre-rendering

How to fetch updated data from CMS if using getStaticProps?


I am fetching blog from CMS inside getStaticProps. Now, I have made changes in the blog in CMS but the updated data is not showing up because getStaticProps fetch this data only during build time. Is there any way to re-fetch the updated data without build?

I only update the blog once or twice in a month and that's why I am feeling getServerSideProps may not be right choice.

I am confused.

I tried researching about it but did not find any answer. For markdown, getStaticProps makes sense as we make changes in the repository and it gets build again, but for CMS, I don't know how to get the updated data.


Solution

  • You can use revalidate prop to load fresh data after certain interval ( in your case once or twice in a month )

    example:

    export async function getStaticProps() {
      const res = await fetch('https://.../posts')
      const posts = await res.json()
     
      return {
        props: {
          posts,
        },
        // Next.js will attempt to re-generate the page:
        // - When a request comes in
        // - At most once every 10 seconds
        revalidate: 10, // In seconds
      }
    

    }

    Do keep in mind that if you want Incremental Static Regeneration (meaning revalidate flag for getStaticProps explained above) then you need to run Next.js server (next start command), without the server there is nothing that could perform requests, update data and generate new static files.

    next export only generates static files once, with the data that was available at the build time.