Next JS Data Fetching using getStaticProps


getStaticProps is a data-fetching method in Next.js that enables Static Generation. This method allows you to fetch data at build time, which is then used to generate static HTML pages. It’s particularly useful for pages where the content does not change often, such as blog posts, product pages, or any other content that can be pre-rendered.

Key Features of getStaticProps

  1. Static Site Generation: Pages using getStaticProps are generated at build time, meaning that the HTML is created once and served to all users, resulting in faster load times and improved performance.

  2. Build-Time Data Fetching: The function fetches data from an API, a database, or any other source during the build process, ensuring that the page has the latest data available at that time.

  3. Automatic Revalidation: With Next.js 12 and later, you can set a revalidation time, allowing the page to be updated in the background while serving static content to users.

Basic Usage

Here’s how to use getStaticProps in a Next.js page component:

// pages/posts/[id].js export default function Post({ post }) { return ( <div> <h1>{post.title}</h1> <p>{post.content}</p> </div> ); } // Fetching data at build time export async function getStaticProps({ params }) { const { id } = params; // Extract the dynamic route parameter (post ID) // Fetch post data from an API or database const res = await fetch(`https://api.example.com/posts/${id}`); const post = await res.json(); // If the post is not found, return a 404 status code if (!post) { return { notFound: true, // This will render a 404 page }; } return { props: { post }, // Pass the post data to the page component as props revalidate: 10, // Optional: Revalidate the page every 10 seconds }; } // Fetching all paths for dynamic routes export async function getStaticPaths() { const res = await fetch('https://api.example.com/posts'); const posts = await res.json(); // Generate paths for each post const paths = posts.map(post => ({ params: { id: post.id.toString() }, // Ensure the ID is a string })); return { paths, fallback: false, // Return a 404 for paths not found }; }

Explanation of the Code

  1. Dynamic Route: The file pages/posts/[id].js defines a dynamic route for blog posts, where id is a variable parameter.

  2. Page Component: The Post component receives the post data as a prop and renders the title and content of the post.

  3. getStaticProps Function:

    • This function is declared as async, allowing the use of await for data fetching.
    • The function receives a context object, which can contain various properties. In this case, we destructure params to get the dynamic id.
    • It fetches the post data from an external API using the provided ID.
    • If the post is not found, returning an object with notFound: true will trigger a 404 page.
    • Finally, it returns an object containing the fetched post data as props and optionally specifies a revalidate time in seconds for Incremental Static Regeneration (ISR).
  4. getStaticPaths Function (used alongside getStaticProps):

    • This function is necessary for dynamic routes. It fetches the list of posts and generates an array of paths to pre-render.
    • Each path object includes a params key with the dynamic route parameters.
    • The fallback property determines how Next.js handles paths not returned by getStaticPaths.

Benefits of Using getStaticProps

  • Performance: Static pages are served from the CDN, leading to fast load times and reduced server load.

  • SEO Friendly: Since the HTML is generated at build time, search engines can index the content effectively, improving SEO.

  • User Experience: Users receive instant page loads without waiting for server responses, creating a smoother experience.

Use Cases for getStaticProps

  • Blog Posts: Fetching and displaying individual blog posts where content does not change frequently.

  • Product Pages: Creating static product detail pages that can be pre-rendered based on product IDs.

  • Documentation: Serving static documentation pages where content is relatively stable.

Summary

getStaticProps is a powerful feature in Next.js for pre-rendering static pages at build time. It allows developers to fetch data and serve it as props to their components, providing fast performance and a great user experience. By leveraging getStaticProps in combination with getStaticPaths, you can efficiently build dynamic pages that benefit from static site generation, making Next.js an excellent choice for modern web applications.