Search code examples
next.jsserver-side-renderingserver-side

Next JS | getStaticPath


  1. Do I need to use getStaticPaths if I'm not going to run the "next export" command?
  2. Can I create a cache structure on the server side using getStaticProps and revalidate for the detail page (/user/1)? Or is there no alternative other than using SWR or getServerSideRender?
  3. Isn't it redundant to get all the data again in the detail(/user/1) page?

Note: User detail page can be refreshed every 60 seconds. Instant update is not important.

export async function getStaticPaths() {
  const res = await fetch('https://.../posts')
  const posts = await res.json()
  const paths = posts.map((post) => ({
    params: { id: post.id },
  }))
  return { paths }
}

export async function getStaticProps({ params }) {
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()
  return { props: { post } }
}


Solution

    1. No . getStaticPaths is useful when it comes to statically generating lot's of pages incrementally .

    2. Yes in next js you can use revalidate cache strategy only when you are generating static pages with getStaticProps like this :

    export async function getStaticProps({ params }) {
      const res = await fetch(`https://.../posts/${params.id}`);
      const post = await res.json();
      // revalidate value is basically in seconds so here it will revalidate the 
      // data every 1 second only If there is an update to it .
      return { props: { post }  , revalidate : 1 }
    }
    
    1. You can use getStaticProps method with getStaticPaths to incrementally generate all pages you need and use pagination .