Learning Next.js Basics

(how to get started on a Next.js project today)

getStaticProps

Next.js can pull resources from a dynamic source (like an API) and pre-statically generate it so that your website load times are fast.

Using the built-in function getStaticProps( ), you are able to call on the resource and create props that can then be used within the page you are building.

Take a look at the below code for an example.

export default function PageName(props) {
    return(
        <>
            <h1>{props.something}</h1>
        </>
        ) 
    }

export async function getStaticProps() {
    const response = await fetch("API url goes here");
    const data = await response.json();

    return {
        props: {
            something: data.something
        }
    }
}

Looking at the getStaticProps( ) section of the code, you'll see that we use async/await to request data from an API then convert that data to json, and then return an object with props: with an object that holds the data that we want to use.

It's important to note a couple things here:

  1. The getStaticProps function must be named getStaticProps
  2. It must return an object with a props object
  3. The data to be used will be assigned to key/value pairs within the props object

Once you understand that, you can see how the props is passed to the PageName function at the top of the code and then used within the return to create an h1 element using the data.

This isn't something you would want to do for unique data (data that is different for every user) or data that is constantly changing or updating, but it is useful for preloading data that can safely be used as a snapshot of that moment.

To see an example you can click my Marvel Character Search project.

Within that site you will note that the information for the character Wolverine is already loaded from the Marvel API upon display of the page and doesn't have to be fetched while the page loads.

But what if you want the information to update as the source updates? That can be achieved by adding revalidate with a time value to the getStaticProps returned object and would look like this:

export async function getStaticProps() {
    const response = await fetch("API url goes here");
    const data = await response.json();

    return {
        props: {
            something: data.something
        },
        revalidate: 10,
    }
}

In the above section of code, the revalidate: 10 will cause the page to regenerate in the background if the page is requested after 10 seconds, and the following page request will have the updated information.

The exact wording Next.js uses to describe this on their docs is:

When a request is made to a page that was pre-rendered at build time, it will initially show the cached page.

What this means is that you are able to get the best of both worlds; The speed of a static generated page with the ability of a dynamic page.

Next up: Nested Routes

Page 5
Page 7