Part 40: Exploring Server-Side Rendering with Next.js: getServerSideProps

[Pages] Data Fetching

[Pages] Data Fetching

In our previous discussions, we've delved into the capabilities of Incremental Static Regeneration (ISR) in Next.js, allowing static pages to be updated at specified intervals. But what if you need your data to be up-to-date every time the page is loaded? This is where getServerSideProps comes into play, offering server-side rendering at runtime for dynamic data fetching.

Understanding Server-Side Rendering with getServerSideProps

The getServerSideProps function in Next.js allows you to fetch data on the server for every request. This means that whenever a user accesses the page, the server fetches the latest data and returns a pre-rendered HTML page. Let's explore how to implement this using a page, index-1c, based on our index-1a page.

Implementing getServerSideProps

The transition from static to server-side rendering is straightforward: simply rename getStaticProps to getServerSideProps. Here's how you can set it up:

// pages/index-1c.js

import Head from 'next/head';
import Title from '../components/Title';
import { getProducts } from '../lib/products';

export async function getServerSideProps() {
  console.log('[HomePage] getServerSideProps()');
  const products = await getProducts();
  return { props: { products } };
}

function HomePage({ products }) {
  console.log('[HomePage] render:', products);
  return (
    <>
      <Head>
        <title>Next Shop</title>
      </Head>
      <main className="px-6 py-4">
        <Title>Next Shop</Title>
        <ul>
          {products.map((product) => (
            <li key={product.id}>
              {product.title}
            </li>
          ))}
        </ul>
      </main>
    </>
  );
}

export default HomePage;

The Benefits and Trade-Offs

With getServerSideProps, you ensure that your page always displays the most current data, similar to client-side fetching but with the added benefit of delivering pre-rendered HTML to the client. This approach is advantageous for dynamic data that must be up-to-date on every request, such as stock prices or user-specific content.

However, there are some trade-offs to consider:

  1. Performance Impact: Each request triggers data fetching and page rendering, leading to slower response times compared to statically generated pages.

  2. Server Load: Frequent data fetching can increase server load and bandwidth usage, especially if the page is accessed frequently.

  3. Scalability Concerns: Server-side rendering can be less scalable than static generation since every request requires computation and backend data access.

Comparing with Development Mode

Interestingly, in development mode (npm run dev), all pages behave like they use getServerSideProps, regardless of whether they use getStaticProps or ISR. This ensures that every change is reflected immediately, making it easier to test your code.

In production mode, however, getServerSideProps stands out by fetching fresh data on every request, while getStaticProps and ISR fetch data at build time or at specified intervals.

Conclusion

getServerSideProps is a powerful tool in Next.js for scenarios where data needs to be current on every page load. It provides the flexibility of server-side rendering with the added benefit of pre-rendered HTML, making it suitable for highly dynamic content.

Nonetheless, it's crucial to weigh the pros and cons and consider the scalability and performance implications. In many cases, using getStaticProps with ISR might be a more efficient solution, as it balances the need for up-to-date data with the performance benefits of static generation.

By understanding and utilizing these features in Next.js, you can create applications that are both dynamic and performant, tailored to the specific needs of your project.

Last updated