DEV Community

Animesh Srivastava
Animesh Srivastava

Posted on

Data Fetching in Next.js

Before diving into this topic I will highly recommend to go through the different types of components and different ways of rendering done in next.js discussed in this post.

1. Client-Side Rendering (CSR)

  • Data Fetching: Data is fetched on the client side, typically inside useEffect or a custom hook.
  • Method: Fetching is done directly within the component using the browser’s fetch API or a client-side data-fetching library like SWR or React Query.
  • Execution: Fetching happens after the page loads and relies on JavaScript for rendering and interactivity.
  • Caching: Dependent on the browser’s caching mechanism and any HTTP headers returned by the server. Client-side caching can also be managed through libraries (e.g., SWR).
  • Use Case: Good for highly interactive, dynamic pages (e.g., dashboards) where SEO is not a priority, or where data is personalized and user-specific.

Example:

import { useEffect, useState } from 'react';

function CSRComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return <div>{data ? data.content : 'Loading...'}</div>;
}

Enter fullscreen mode Exit fullscreen mode

2. Server-Side Rendering (SSR)

  • Data Fetching: Data is fetched on the server for each request, using getServerSideProps.
  • Method: getServerSideProps executes on every request, retrieving data and passing it to the component as props.
  • Execution: Runs on the server at request time, generating fresh HTML for each request.
  • Caching: You can configure server or CDN caching, but by default, it generates new HTML for every request.
  • Use Case: Ideal for frequently updated or user-specific data, where the latest data is essential on every load (e.g., personalized dashboards or live data feeds).

Example:

export async function getServerSideProps() {
  const res = await fetch('<https://api.example.com/data>');
  const data = await res.json();

  return { props: { data } };
}

function SSRPage({ data }) {
  return <div>{data.content}</div>;
}

Enter fullscreen mode Exit fullscreen mode

3. Static Site Generation (SSG)

  • Data Fetching: Data is fetched once at build time using getStaticProps.
  • Method: getStaticProps retrieves data at build time, generating a static HTML file that is cached until the next build.
  • Execution: Runs only during the build process, making the page content static.
  • Caching: Content is fully cacheable by CDNs and does not change until the site is rebuilt.
  • Use Case: Ideal for static or rarely changing content (e.g., blog posts, product pages) where load speed and SEO are a priority.

Example:

export async function getStaticProps() {
  const res = await fetch('<https://api.example.com/data>');
  const data = await res.json();

  return { props: { data } };
}

function SSGPage({ data }) {
  return <div>{data.content}</div>;
}

Enter fullscreen mode Exit fullscreen mode

4. Incremental Static Regeneration (ISR) (SSG with Regular Updates)

  • Data Fetching: Data is fetched at build time but can be refreshed at regular intervals using the revalidate option in getStaticProps.
  • Method: getStaticProps fetches data and uses the revalidate field to specify an interval for regeneration.
  • Execution: Initially generated at build time, but after the specified interval, the page will be regenerated in the background on the next request.
  • Caching: Cached globally on CDNs with periodic regeneration based on the revalidate interval.
  • Use Case: Ideal for semi-static content that needs occasional updates (e.g., product listings, news articles) without needing to rebuild the entire site.

Example with ISR:

export async function getStaticProps() {
  const res = await fetch('<https://api.example.com/data>');
  const data = await res.json();

  return {
    props: { data },
    revalidate: 60, // Regenerates every 60 seconds
  };
}

function ISRPage({ data }) {
  return <div>{data.content}</div>;
}

Enter fullscreen mode Exit fullscreen mode

Summary Table

Rendering Method Data Fetching Method Execution Time Caching and Update Use Case
CSR Inside useEffect on client After page load (client) Browser cache Interactive, user-specific content
SSR getServerSideProps On every request (server) Optional CDN Frequently updated, dynamic content
SSG getStaticProps At build time CDN cached Static, rarely updated content
ISR getStaticProps with revalidate At build + intervals CDN with periodic updates Semi-static with occasional updates

Top comments (0)