DEV Community

Cover image for Next.js Data Fetching: getStaticProps vs getServerSideProps
Mike Varenek
Mike Varenek

Posted on

Next.js Data Fetching: getStaticProps vs getServerSideProps

Next.js, a popular React framework, empowers developers to build dynamic and efficient web applications. A crucial aspect of Next.js is its ability to fetch data, and it provides two key functions for this purpose: getStaticProps and getServerSideProps. Understanding these functions is essential for creating optimal user experiences in your Next.js projects.

getStaticProps:

Function: getStaticProps is executed during the build time, fetching data before the page is served to the user.
Benefits:
Performance: Pre-rendering pages with getStaticProps leads to faster initial page loads, as the data is already available and doesn't require additional requests on the client-side.
SEO: Since the content is pre-rendered, search engines can easily crawl and index your pages, improving your Search Engine Optimization (SEO).
Scalability: Pre-rendered pages can be effectively cached by Content Delivery Networks (CDNs), further enhancing performance and scalability.
Use Cases:
Content that doesn't change frequently, like blog posts, product listings, or static landing pages.
Data fetched from headless CMS systems or other sources that are accessible during build time.

// pages/blog/[slug].js

export async function getStaticProps(context) {
  const slug = context.params.slug;
  const response = await fetch(`https://api.example.com/posts/${slug}`);
  const postData = await response.json();

  return {
    props: { postData },
  };
}

export default function BlogPost({ postData }) {
  return (
    <div>
      <h1>{postData.title}</h1>
      <p>{postData.content}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, getStaticProps fetches data for a specific blog post based on its slug during build time. The fetched data is then passed as props to the BlogPost component, allowing it to render the post content.

getServerSideProps:

Function: [getServerSideProps](https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props) runs on every request to the server, fetching data just before the page is sent to the user.
Benefits:
Dynamic Content: Ideal for scenarios where data is constantly changing, like displaying live news feeds, personalized recommendations, or user-specific information.
Authentication: Useful for pages requiring user authentication, as data can be fetched after verifying the user's identity.
Use Cases:
Pages displaying real-time data or personalized content based on user interaction.
Data that requires user authentication or authorization before being accessible.

// pages/products.js

export async function getServerSideProps() {
  const response = await fetch(`https://api.example.com/products`);
  const products = await response.json();

  return {
    props: { products },
  };
}

export default function Products({ products }) {
  return (
    <div>
      <h2>Products</h2>
      <ul>
        {products.map((product) => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here, getServerSideProps runs on every request to the /products page, fetching the latest product list from the API before rendering the page for the user. This ensures users always see the most up-to-date product information.

Choosing the Right Tool

The choice between getStaticPropsand getServerSidePropsdepends on your specific requirements:

For pre-rendering static content and prioritizing SEO and performance, getStaticProps is the way to go.
For dynamic content that updates frequently or requires user-specific data, getServerSideProps provides the necessary flexibility.

Top comments (0)