codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚛️

React.js

50 / 61 topics
48Introduction to Server-Side Rendering (SSR)49Next.js: An Overview50Using getStaticProps and getServerSideProps in Next.js51Dynamic Imports in Next.js
Tutorials/React.js/Using getStaticProps and getServerSideProps in Next.js
⚛️React.js

Using getStaticProps and getServerSideProps in Next.js

Updated 2026-04-20
2 min read

Introduction

In this advanced section of our React.js course, we will delve into two powerful features provided by Next.js for data fetching: getStaticProps and getServerSideProps. These functions allow you to fetch data at build time or request time, respectively, which can significantly enhance the performance and user experience of your applications.

Overview

  • getStaticProps: Fetches data at build time. The page is pre-rendered with the fetched data.
  • getServerSideProps: Fetches data on each request. The page is generated on every request.

Both functions are asynchronous and return an object containing a props key, which can be passed to your component as props.

When to Use getStaticProps

Use getStaticProps when you want to pre-render a page at build time with the data that's required for the initial render. This is ideal for pages where the content doesn't change often or can be generated ahead of time.

Example: Fetching Blog Posts at Build Time

// app/posts/[id]/page.js
import { useRouter } from 'next/navigation';

export async function generateStaticParams() {
  // Fetch all blog post IDs from an API
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();

  // Generate paths for each blog post
  return posts.map((post) => ({
    id: post.id.toString(),
  }));
}

export async function getStaticProps({ params }) {
  // Fetch the blog post by ID
  const res = await fetch(`https://api.example.com/posts/${params.id}`);
  const post = await res.json();

  return {
    props: {
      post,
    },
    revalidate: 10, // Optional: Regenerate the page every 10 seconds
  };
}

export default function Post({ post }) {
  const router = useRouter();
  if (router.isFallback) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
}

Explanation

  • generateStaticParams: Determines the paths that Next.js should pre-render at build time. It returns an array of objects, each containing a params key with the dynamic route parameters.
  • getStaticProps: Fetches data for a specific path generated by generateStaticParams. The fetched data is passed as props to the page component.

When to Use getServerSideProps

Use getServerSideProps when you need to fetch data on each request. This is suitable for pages where the content changes frequently or needs to be up-to-date with every request.

Example: Fetching Real-Time Data

// app/real-time-data/page.js
export async function getServerSideProps() {
  // Fetch real-time data from an API
  const res = await fetch('https://api.example.com/real-time');
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}

export default function RealTimeData({ data }) {
  return (
    <div>
      <h1>Real-Time Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

Explanation

  • getServerSideProps: Fetches data on each request. The fetched data is passed as props to the page component.

Best Practices

  1. Data Caching: Use the revalidate option in getStaticProps to control how often a page should be regenerated. This helps reduce server load and improves performance.
  2. Error Handling: Implement error handling in both getStaticProps and getServerSideProps to manage failed data fetches gracefully.
  3. Fallbacks: Use the fallback option in generateStaticParams to handle dynamic routes that are not pre-rendered at build time.
  4. Performance Optimization: Minimize the amount of data fetched by only requesting what's necessary for each page.

Conclusion

In this tutorial, we explored how to use getStaticProps and getServerSideProps in Next.js to fetch data efficiently. By understanding when to use each function and implementing best practices, you can create highly performant and dynamic React applications.

Remember, the choice between getStaticProps and getServerSideProps depends on your specific use case and requirements. Use getStaticProps for pre-rendering pages at build time and getServerSideProps for fetching data on each request.


PreviousNext.js: An OverviewNext Dynamic Imports in Next.js

Recommended Gear

Next.js: An OverviewDynamic Imports in Next.js