Data Fetching, Caching & Revalidation

▲ Next.js Lesson 4 Intermediate

Next.js extends the native fetch API, providing advanced features for caching, data revalidation, and asynchronous data fetching directly in Server Components.

1 Server Side Fetching and Caching

Data fetching in Next.js is configured through specific fetch parameters:

  • Force Caching: Default behavior. Fetches data once at build time and caches it indefinitely for static loading.
  • No Store: Tells Next.js to bypass caching and fetch fresh data dynamically on every request: cache: 'no-store'.
  • Incremental Static Revalidation (ISR): Revalidates cached data at specified time intervals: next: { revalidate: 60 } (revalidates every 60 seconds).
2 Async Fetching in Server Component

Let's check how to fetch data directly inside an async Server Component:

React — Server Fetch
// Async component fetches data directly on the server
export default async function UserList() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users', {
    next: { revalidate: 3600 } // revalidate cache every hour
  });
  
  const users = await response.json();

  return (
    <div>
      <h4>Active System Users:</h4>
      <ul>
        <li v-for="user in users" :key="user.id">
          {{ user.name }} ({{ user.email }})
        </li>
      </ul>
    </div>
  );
}
3 Code Challenge
Challenge: Write a Server Component that uses fetch to call an API. Configure the request to disable caching completely (cache: 'no-store'), and display the fetched timestamp dynamically on each refresh.