How to use getStaticProps in Next.js

How to use getStaticProps in Next.js

A beginner-oriented approach to how to use getStaticProps in Next.js

🔓 What you'll get from this 6-minute read

  • You'll learn more about page pre-rendering and the corresponding data fetching processes in Next.js.

  • You'll understand the difference between Next.js using page pre-rendering and plain React applications.

  • You'll get to know the getStaticProps function as a method of fetching external data for use during static generation.

📰 Page pre-rendering

One of the main advantages of Next.js compared to React is the so-called pre-rendering of a page. Due to this concept, Next.js pre-renders every page. React, on the other hand, solely relies on the client-side with JavaScript taking full responsibility for generating the page. Such pre-rendering is, for example, helpful in terms of SEO since all the content of the page has already been generated in advance.

If we compare a Next.js application with a plain React application, we can also directly observe the concept of hydration. Hydration in this context can be understood as the process where JavaScript steps in after a page has been loaded by the browser and then manages to make the page fully interactive.

💧 Hydration

In a plain React application, no page pre-rendering is happening. Therefore, no actual content was rendered at the initial load of the page. Instead, only after the initial load of JavaScript steps in to make the React app interactive - all React components get initialized during this step. This exact process of making the page interactive is called hydration.

In a Next.js application page, pre-rendering is actually happening. Therefore, HTML was already generated (pre-rendered) at the initial load of the page. After that, JavaScript steps in as it did in the plain React application and also helps here to make the Next.js application interactive, so all your React components actually start to work. This process of making the page interactive is again called hydration.

🔧 getStaticProps

While this whole pre-rendering is already pretty exciting, an additional advantage of this concept is the fact that you can use approaches to reach out to the server-side of Next.js to hand over external fetched data from a databank, for example, which then gets pre-rendered. getStaticProps is one way to make use of that concept.

There are actually two ways that pre-rendering in Next.js can work. Right now I want to focus on the most important approach which is used most of the time - the static generation.

At the static generation, your application creates its HTML, which works with minimal JavaScript at the build time. This pretty much means that your corresponding page pre-renders before the initial load, like I was referring to above.

Actually, this is the standard process for every Next.js page. Even if you don't reach out to fetch some data from the server-side or whatever, the page will get pre-rendered by static generation. You can use getStaticProps whenever you are trying to fetch some external data for this static generation.

🔨 Code example

Next.js will first execute the getStaticProps function before the page functions get executed. As a result, all the data we pass in as props during the getStaticProps can be used on this specific page as props. The code that you use in the getStaticProps function doesn't get exposed to the client-side. Anything that you pass to the props return, however, will.

Please see the following harcoded example of the usage of the getStaticProps function. Have in mind that I'm using TypeScript here. If you are using JavaScript you can ignore the starsInterface:

interface starsInterface {
  'stars': {
    id: string,
    name: string,
    description: string,
    link: string
  }[]
}

const Home = (props: { stars: starsInterface['stars'] }) => {
  return (
      {props.stars.map(item => {
        return (
          <div key={item.id}>
            <h2>{item.name}</h2>
            <p>{item.description}</p>
            <a href={item.link}>More Information about this star</a>
          </div>
        )})}
    >
  )
}

export async function getStaticProps() {
  return {
    props: {
      stars: [
              { 
                "id": "St2-18", 
                "name": "Stephenson 2-18", 
                "description": "Stephenson 2-18 is a red supergiant (RSG) or possible extreme red hypergiant (RHG) star in the constellation of Scutum.", 
                "link": "https://en.wikipedia.org/wiki/Stephenson_2-18" 
              },
              { 
                "id": "UY-SC", 
                "name": "UY Scuti", 
                "description": "UY Scuti is an extreme red hypergiant or red supergiant star in the constellation Scutum.", 
                "link": "https://en.wikipedia.org/wiki/UY_Scuti"
              },
              { 
                "id": "RSGC1", 
                "name": "RSGC1-F01", 
                "description": "RSGC1-F01 is a red supergiant located in the RSGC1 open cluster in the constellation of Scutum.", 
                "link": "https://en.wikipedia.org/wiki/RSGC1-F01"
              }
            ]
     }
  }
}
export default Home

Thus, we basically created a standard Home page which returns some JSX where we mapped through the stars array which was given to the props. At the bottom of the code, you see the actual getStaticProps function. You can see that I'm basically just putting in an array with objects.

Since the getStaticProps gets acknowledged by Next.js (it's important that you actually name it getStaticProps), it executes this function before the page itself is created. Therefore, we are able to use the passed in data in getStaticProps as props for your page. When we now load our Next.js application for this page, we see the following:

result.PNG

All our data was successfully transferred to the page content and this whole process of page pre-rendering worked out. Therefore, you are also able to find this content in your page source - that's, for example, helpful for SEO objectives:

console.PNG

❗ Have the following in mind

This is a hardcoded example since the focus was on the getStaticProps function itself and not on how to fetch data from a databank, API or external backend file, for example.

For any actual case, you would fetch your data within the getStaticProps function and then return the result of that fetching process to the props object, as you saw with the stars key and its array of three stars as a value, like I presented above.

Besides that, I didn't focus on the context parameter of getStaticProps which can be quite helpful on some occasions. This quick guide didn't cover everything that can be said about the getStaticProps function.

✅ Conclusion

As referred to, getStaticProps isn't the only mechanism to fetch external data for the pre-rendering process. However, it's the most common one and probably should also be the first one to wrap your head around while getting familiar with the pre-rendering and data fetching topics in Next.js.

📃 Resources