Johan Benjaminsson

Johan Benjaminsson

johan.benjaminsson@gmail.com, Mastodon

4 Ways of getting data in NextJS

Static Site Generation (SSG)

This technique fetches the data at build time using getStaticProps and generates the static html pages. This is good for when you have data that does not change that often. Ie getting data for an FAQ page from a CMS. This blog post uses this technique since it is just a .mdx deployed alongside the rest of the web page.

Snippet for displaying this post:

export async function getStaticProps({ params }) {
  const postData = await getPostData(params.id);
  return {
    props: {
      postData
    }
  };
}

If you don't need to fetch data from anywhere NextJS will use this techique to deliver the page by default.

Caveat: This is only possible on NextJS pages and cannot be used in regular components. When to use:

Incremental Static Regeneration (ISR)

If we want the data to be a bit more up to date but we don't really need it to be updated in real time, we can use add the line revalidate to getStaticProps:

export async function getStaticProps({ params }) {
  const postData = await getPostData(params.id);
  return {
    props: {
      postData
    },
    revalidate: 60
  };
}

Technically this is a serverless function that after 60 seconds makes this data stale. If someone visits this post after 60 seconds he will get the same stale data but triggers a regeneration for the next visitor.

I use this for displaying my latest movie reviews from Letterboxd on the front page. This is the perfect use case for this since it is ok if a user doesn't see my latest review.

Server Side Rendering (SSR)

With GetServersideProps you can build the page on the server and deliver it directly to the client. This will make the server work to create an HTML page on every request so it will not load as fast. But if you need to check on the server that the user is authenticated before showing any data this is the way to go.

export async function getServerSideProps() {
  const pageData = await getPageData(params.id);
  return { props: { pageData } };
}

Client Side Rendering (CSR)

This is a combination of pre rendering the html page (SSG or ISR) but still want some of the data on the page to be real time.

NextJS has a hook for this called useSWR (external library) but you can also use React Query that has some more functionality and dev tools (but a bigger bundle size).

If i was to implement comments on this blog post i would use this technique!

const {
  isLoadingComments,
  data
} = useQuery('comments', getComments);

return isLoadingComments
  ? 'Loading comments...'
  : <CommentList data={data} />;