Table of contents
1.
Introduction
2.
Static Site Generation
2.1.
getStaticProps: 
2.2.
getStaticPaths:
3.
getStaticProps
4.
When to use getStaticProps?
5.
Benefits
6.
FAQs
7.
Key Takeaways:
Last Updated: Mar 27, 2024

Data fetching using getStaticProps

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We might need to render the content of an application sometimes, depending on the requirements and use cases of the application. For this, next.js provides us with a technique called data fetching. The data fetching in Next.js allows the user to change the application's content. This includes pre-rendering the content with Server-side Rendering or Static Generation and updating or creating content at the runtime with Incremental Static Regeneration. There are different strategies used for fetching data. They are

  • Client-side rendering
  • Server-side rendering
  • Static site generation
  • ​Incremental static regeneration.


We have different methods to fetch data in different strategies. The methods used are

  • getStaticProps(Static site generation)
  • getStaticPaths(Static site generation)
  • getServerSideProps(Server-side rendering)
  • getInitialProps(Server-side rendering)
  • useEffect(Client-side rendering)


Note: The getInitialProps() method is no longer used and will be deprecated soon.

This article will discuss Static Site Generation and the getStaticProps method with detailed code.

Static Site Generation

Static Site Generation(SSG) is the process of compiling and rendering a website at the build time. The output is the HTML file, including CSS and JavaScript files. In Next.js, Static Site Generation allows the user to access the entire content of a webpage on the first load and loads the scripts with the remaining changes on each request. There are two types of Static Site Generation; with and without data. We use two methods in Static Site Generation; getStaticPaths and getStaticProps. 

getStaticProps: 

The getStaticProps() method is used to fetch and render the data of a webpage and at the build time using the props returned by this method.

getStaticPaths:

The getStaticPaths() method works similar to getStaticProps(), but it is used to fetch data and pre-render the pages/content for dynamic paths.

Let’s explore more about getStaticProps() in this article.

getStaticProps

The getStaticProps() function can be used inside a web page to fetch or render the data at the build time using the props this method returns. Once the application is built, it will refuse to refresh the data until we run another build. It is an async function that allows the web pages to be generated statically, so this method has the fastest load times. The data is rendered ahead of the user’s request, improving the page's Search Engine Optimization(SEO) of the web page. The code written inside the getStaticProps method is not visible to the client. 

Whenever the client loads the page, code inside getStaticProps is executed first and, then it returns the object to the main page component. It always returns the object and gets executed before the page component. The syntax for the getStaticProps method is given below.

export async function getStaticProps(context) {
  return {
    props: {}, // will be passed to the page as props
  }
}
You can also try this code with Online Javascript Compiler
Run Code


The parameter context in the getStaticProps() method is an object and has the following keys:

  • params: params contains the route parameters for all the pages using dynamic routes.
  • preview: The preview is set to true only if the page is in the preview mode; otherwise, it is undefined.
  • previewData: The previewData contains the preview data.
  • locale: contains the active locale.
  • locales: contains all the supported locales.
  • defaultLocale: contains the configured default locale.


getStaticProps() returns the object with the following keys:

  • props: props that are received by the page component.
  • revalidate: The amount of time after which the page re-generation occurs.
  • notFound: The boolean value that allows the page to return a 404 status.

When to use getStaticProps?

We use getStaticProps when:

  • The data required to render the web page is available at the build time ahead of a user’s request.
  • The data comes from a headless Content Management System(CMS).
  • The data can be cached publicly.
  • The page must be pre-rendered and fast.
     
export async function getStaticProps(context) {
  const res = await fetch(`https://.../data`)
  const dataFetched = await res.json()
  if (!data) {
    return {
      notFound: true,
    }
  }
  return {
    props: { dataFetched }, // will be passed to the page component as props
  }
}
You can also try this code with Online Javascript Compiler
Run Code


In the above code, the function fetches the data and stores it in the variable dataFetched. If the data fetched is available, it sets the notFound value to false and returns the props; else, it sets the value to true and returns a 404 error.

We have another situation where we use a dynamic page, and the path depends on external data. Then we have to use the getStaticPaths function along with getStaticProps. 

export async const getStaticProps = ({ params }) => {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`);
  const data = await res.json();
  return {
    props: { data },
  };
}
export async function getStaticPaths() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  const posts = await res.json();
  const paths = posts.map(({ id }) => ({ params: { id: `${id}` } }));
  return {
    paths,
    fallback: false,
  };
}
You can also try this code with Online Javascript Compiler
Run Code


In the above code, we are fetching the data for a dynamic page, and we used the getStaticPaths function here to tell the page which routes should be pre-loaded and to check which routes have been created.

Benefits

We have a lot of benefits of using the getStaticProps method; a few of them are listed below.

  • It allows the page to be generated statically.
  • Generates the fastest load times.
  • Improves the SEO of the page, as the data is rendered before it reaches the client.
  • It is used inside a page to fetch data at the build time.
  • The code inside the function is not visible to the client.

FAQs

  1. What is data fetching in next.js?
    The data fetching in Next.js allows the user to change the application's content. This includes pre-rendering the content with Server-side Rendering or Static Generation and updating or creating content at the runtime with Incremental Static Regeneration.
     
  2. What are the ways of fetching data in nextJs?
    The different strategies used for fetching data are; Client-side rendering, Server-side rendering, Static site generation, and ​Incremental static regeneration.
     
  3. When should I use Static Site Generation?
    The getstaticProps method should be used to fetch an application's data that doesn’t change often.

Key Takeaways:

We discussed Data fetching, strategies of data fetching, Static SIte generation, and getStaticProps in this article. 

Next.js is interesting, right? To master web development, you also need to learn the frameworks and libraries. To learn more about Next.js check this web development course we suggest you and become an expert. 

Happy Learning!

Live masterclass