#dynamic ISR revalidation interval

1 messages · Page 1 of 1 (latest)

karmic hareBOT
#

Hi @spring oyster. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, the revalidate field returned from getStaticProps can be dynamic. You can set it based on the success or failure of your data fetching. If the data fetching is successful, you can set revalidate to 3600 seconds (1 hour). If the data fetching fails, you can set revalidate to 1 second so that it tries again on the next page request.

Here's an example based on the code provided in the extracts:

export async function getStaticProps() {
  let revalidateTime;
  const res = await fetch('<https://.../posts'>)
  const posts = await res.json()

  if (!res.ok) {
    // If there is a server error, you might want to
    // throw an error instead of returning so that the cache is not updated
    // until the next successful request.
    revalidateTime = 1; // In seconds
    throw new Error(`Failed to fetch posts, received status ${res.status}`)
  } else {
    // If the request was successful, return the posts
    // and revalidate every 1 hour.
    revalidateTime = 3600; // In seconds
  }

  return {
    props: {
      posts,
    },
    revalidate: revalidateTime,
  }
}

This code will attempt to fetch posts from a specified URL. If the fetch is successful, it sets revalidate to 3600 seconds (1 hour). If the fetch fails, it sets revalidate to 1 second and throws an error.

Please note that if there is an error inside getStaticProps when handling background regeneration, or you manually throw an error, the last successfully generated page will continue to show. On the next subsequent request, Next.js will retry calling getStaticProps source (https://nextjs.org/docs/pages/building-your-application/data-fetching/incremental-static-regeneration).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@spring oyster kapa.ai is still learning and improving, please let us know how it did by reacting below