Learn Next.js · 5/15

Data Fetching: Getting Your Data

7 min read

Data Fetching: Getting Your Data Fetching data in a web application is like a restaurant getting its ingredients. You need fresh, high-quality ingredients (data) to prepare a delicious meal (your web page) for your customers (users). In Next.js, how and when you get these ingredients can dramatically affect your restaurant's efficiency (website's performance) and the freshness of the meal (the data displayed).

This guide will walk you through the primary ways to fetch data in Next.js, from the server to the client, ensuring you can build fast, scalable, and modern web applications.


📥 1. Server-Side Fetching with the Native fetch API

The Problem: Imagine a user visits a product page. They expect to see the latest price and stock information immediately. If you fetch this data on the client-side (in the user's browser), they might see a loading spinner before the content appears, which isn't a great first impression.

The Solution: Fetch the data on the server before the page is sent to the browser. This way, the user receives a fully rendered HTML page with all the necessary data already included. It's like having a dish fully prepared and ready to serve the moment a customer orders it.

In Next.js, especially with the App Router, the native fetch API is extended to allow you to fetch data on the server within your components. This is the recommended and most common way to handle server-side data fetching.

How it Works (Under the Hood):
When a request is made for a page, Next.js on the server will see your async component and the fetch call within it. It will pause the rendering of that component, go and get the data from the API, and once the data is available, it will resume rendering the component with that data. Finally, it sends the complete HTML to the browser.

Example: Fetching a List of Products

Let's create a page that displays a list of products fetched from an external API.

jsx
// app/products/page.js

async function getProducts() {
  const res = await fetch('https://api.example.com/products');

  // Recommendation: handle errors
  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data');
  }

  return res.json();
}

export default async function ProductsPage() {
  const products = await getProducts();

  return (
    <main>
      <h1>Our Products</h1>
      <ul>
        {products.map((product) => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    </main>
  );
}

Key Points:

  • We're using an async function for our component (ProductsPage). This is a key feature of React Server Components.
  • The fetch call happens on the server, not in the user's browser.
  • The page is fully rendered on the server and sent to the client as HTML.

This approach is fantastic for SEO and for pages where the data needs to be fresh on every request.


🔄 2. Caching Strategies: Static Rendering vs. Dynamic Rendering

Now that you know how to fetch data, the next big question is: how often should you fetch it? Going back to our restaurant analogy, if your menu changes only once a day, you don't need to reprint it for every single customer. That would be a waste of paper and time.

The Problem: Fetching data for every single user request can be slow and expensive, especially if the data doesn't change often.

The Solution: Caching! Next.js has a powerful built-in caching system that works with fetch. By default, Next.js will cache the results of your fetch requests.

Static Rendering (Default)

This is the default behavior. Next.js will fetch the data at build time (when you deploy your application) and then reuse the same data for every user until you rebuild your site.

  • Real-life scenario: A blog post. Once it's published, the content doesn't change. So, you can fetch it once, build the page, and serve that static page to everyone. It's incredibly fast.

Example:

jsx
// This will be fetched once at build time and cached indefinitely by default.
async function getBlogPost(slug) {
  const res = await fetch(`https://api.example.com/posts/${slug}`);
  return res.json();
}

Dynamic Rendering

This is for when you need fresh data on every request. You tell Next.js not to cache the data.

  • Real-life scenario: A user's shopping cart page. The content is unique to each user and changes frequently. You need to fetch it fresh every time they visit the page.

Example: Opting Out of Caching

To make a fetch request dynamic, you can set the cache option to 'no-store'.

jsx
// This will be fetched on every request.
async function getShoppingCart(userId) {
  const res = await fetch(`https://api.example.com/cart/${userId}`, { cache: 'no-store' });
  return res.json();
}
Strategy When to Use Analogy
Static Rendering Data that rarely changes (blog posts, documentation, marketing pages). A printed restaurant menu.
Dynamic Rendering Data that changes often or is user-specific (shopping carts, user profiles, dashboards). A digital menu board that updates in real-time.

🌬️ 3. On-Demand Revalidation: Keeping Data Fresh

Okay, so static rendering is fast. But what if your "static" blog post has a typo? You fix it in your CMS, but your site is still showing the old version because the data was cached at build time. Do you have to redeploy your entire website just to fix a small typo? That sounds... dramatic.

The Problem: Statically generated pages can become stale if the underlying data changes.

The Solution: On-demand revalidation. This allows you to manually tell Next.js to invalidate its cache for a specific page and re-fetch the data, without needing a full redeployment.

How it Works:
You can set up a webhook or an API route that, when triggered, will revalidate a specific path. For example, your CMS could send a request to this webhook whenever a blog post is updated.

Next.js also allows for time-based revalidation.

Example: Time-based Revalidation

You can tell fetch to cache the data for a certain amount of time. After that time expires, the next user who visits the page will get a fresh version.

jsx
// Re-fetch the product list every hour (3600 seconds)
async function getProducts() {
  const res = await fetch('https://api.example.com/products', { next: { revalidate: 3600 } });
  return res.json();
}

This is a great middle-ground. You get the speed of static pages for most users, but the data is automatically refreshed periodically. It's like your restaurant updates its "specials" board every hour.


🙋‍♂️ 4. Client-Side Fetching: SWR and React Query Basics

Sometimes, you need to fetch data directly from the browser.

The Problem: What about data that is highly dynamic and specific to a user's interaction on a page after it has loaded? For example, a user types into a search bar, and you want to show them live results. Server-side fetching can't help here because the page is already loaded.

The Solution: Client-side data fetching. You use libraries within your React components that run in the browser to fetch, cache, and update data.

Two of the most popular libraries for this in the React ecosystem are SWR and React Query. They are incredibly powerful and handle complex scenarios like caching, revalidation on window focus, and more, right out of the box.

When to Use Client-Side Fetching:

  • For data that is part of a highly interactive UI (e.g., search results as you type).
  • For user-specific data on a page that is otherwise static (e.g., a user's notification count in the header).

To use these, you need to mark your component as a Client Component with the "use client"; directive at the top of your file.

A Simple Example with SWR:

First, you'd need to install it:
npm install swr

Then, you can use it in a component.

jsx
// app/components/UserNotifications.js
"use client";

import useSWR from 'swr';

const fetcher = url => fetch(url).then(res => res.json());

export default function UserNotifications() {
  const { data, error } = useSWR('/api/user/notifications', fetcher);

  if (error) return <div>Failed to load</div>;
  if (!data) return <div>Loading...</div>;

  return <div>You have {data.count} notifications.</div>;
}

What useSWR does is pretty magical:

  1. It fetches the data from /api/user/notifications.
  2. While it's fetching, data is undefined, so you can show a "Loading..." message.
  3. Once the data arrives, the component re-renders to show the notification count.
  4. If the user navigates away and then comes back to the tab, SWR will automatically re-fetch the data to make sure it's fresh! ✨

React Query works in a very similar way, offering a rich set of features for managing client-side data. The choice between them often comes down to personal or team preference.

📚 References for Extra Reading

Challenge

You are tasked with building a product listing page in a Next.js application that uses multiple data fetching strategies to optimize performance and data freshness.

Your goal is to complete the code for three components, each with a specific data fetching requirement. Assume each component block resides in its own file as commented in the initial code.

  1. ProductPage (The Page Component):

    • This is an async Server Component.
    • It should fetch a list of products from https://api.example.com/products.
    • This data should be statically generated but revalidated every hour (3600 seconds) to ensure it stays reasonably fresh.
    • It should then map over the fetched products and render a StockStatus component for each one.
  2. StockStatus (A Child Server Component):

    • This is an async Server Component that accepts a productId prop.
    • Inside this component, fetch the specific stock level for the given product ID from https://api.example.com/products/${productId}/stock.
    • Stock data changes constantly and must be fetched dynamically on every request. Ensure this fetch call is never cached by the server.
  3. Recommendations (A Client Component):

    • This component will be used to fetch and display user-specific recommendations.
    • Since the data is user-specific and requires interactivity, it must be fetched on the client-side.
    • Correctly configure this component to be a Client Component. You do not need to write the actual data-fetching logic (e.g., using useEffect or SWR), only the directive that enables it.

Expected result

Your completed code should correctly implement three distinct Next.js data fetching patterns within the provided component structure.

  1. In ProductPage:

    • The function must be async.
    • It must contain an await call to fetch('https://api.example.com/products', ...).
    • The fetch options object must correctly specify time-based revalidation: { next: { revalidate: 3600 } }.
  2. In StockStatus:

    • The function must be async.
    • It must contain an await call to fetch from the dynamic stock endpoint (e.g., `https://api.example.com/products/${productId}/stock`).
    • The fetch options object must prevent caching: { cache: 'no-store' }.
  3. In Recommendations:

    • The line "use client"; must be placed at the very top of the code block for the Recommendations component, before the function definition. This correctly designates it as a Client Component.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.