Pre-rendering and Data Fetching

Fetching Data at Request Time

If you need to fetch data at request time instead of at build time, you can try Server-side Rendering:

To use Server-side Rendering, you need to export getServerSideProps instead of getStaticProps from your page.

Using getServerSideProps

Here’s the starter code for getServerSideProps. It’s not necessary for our blog example, so we won’t be implementing it.

export async function getServerSideProps(context) {
  return {
    props: {
      // props for your component
    },
  };
}

Because getServerSideProps is called at request time, its parameter (context) contains request specific parameters.

You should use getServerSideProps only if you need to pre-render a page whose data must be fetched at request time. Time to first byte (TTFB) will be slower than getStaticProps because the server must compute the result on every request, and the result cannot be cached by a CDN without extra configuration.

Client-side Rendering

If you do not need to pre-render the data, you can also use the following strategy (called Client-side Rendering):

  • Statically generate (pre-render) parts of the page that do not require external data.
  • When the page loads, fetch external data from the client using JavaScript and populate the remaining parts.

This approach works well for user dashboard pages, for example. Because a dashboard is a private, user-specific page, SEO is not relevant, and the page doesn’t need to be pre-rendered. The data is frequently updated, which requires request-time data fetching.

SWR

The team behind Next.js has created a React hook for data fetching called SWR. We highly recommend it if you’re fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. We won’t cover the details here, but here’s an example usage:

import useSWR from 'swr';

function Profile() {
  const { data, error } = useSWR('/api/user', fetch);

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;
  return <div>hello {data.name}!</div>;
}

Check out the SWR documentation to learn more.

That’s It!

In the next lesson, we’ll create pages for each blog post using dynamic routes.

Again, you can get in-depth information about getStaticProps and getServerSideProps in the Data Fetching documentation.

Quick Review: When should you use Client-side rendering?