0Pricing
Next.js 15 Fullstack Web Apps · Lekcja

Strategie buforowania po stronie serwera

Naucz się buforować dane na serwerze za pomocą opcji `fetch` i ponownej walidacji w celu poprawy wydajności.

Strategie buforowania po stronie serwera to bezpłatna lekcja Next.js 15 Fullstack Web Apps na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Next.js 15 Fullstack Web Apps, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Next.js 15 Fullstack Web Apps zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Why Server-Side Caching?

In Next.js, server-side caching is crucial for building fast and efficient web applications. It helps reduce load times and server strain.

  • Performance: Delivers content faster to users.
  • Cost Reduction: Less frequent data fetches mean fewer API calls, potentially saving money.
  • Scalability: Handles more users without overloading your backend.

We'll explore how Next.js leverages the native fetch API for powerful caching.

Next.js `fetch` & Caching Defaults

When you use the native fetch API in Next.js Server Components, it automatically caches data by default. This is like having a built-in data store.

By default, fetch requests are cached using the 'force-cache' strategy. This means Next.js will look for a cached response first and use it if available, only fetching new data if no cache entry exists.

Disabling Cache: `cache: 'no-store'`

Sometimes, you need to ensure data is always fresh, like for real-time dashboards or sensitive user information. For these cases, you can disable caching for specific fetch requests.

Using cache: 'no-store' tells Next.js to always fetch fresh data from the origin server and never store it in the cache. This is useful for highly dynamic or frequently changing content.

`no-store` in Action

Here's how you'd use cache: 'no-store' in a Server Component to ensure you always get the latest user data.

async function getUserProfile(userId) {
  const res = await fetch(`https://api.example.com/users/${userId}`, {
    cache: 'no-store' // Always fetch fresh data
  });
  if (!res.ok) {
    throw new Error('Failed to fetch user profile');
  }
  return res.json();
}

export default async function ProfilePage({ params }) {
  const user = await getUserProfile(params.userId);
  return (
    <div>
      <h1>Welcome, {user.name}</h1>
      <p>Email: {user.email}</p>
    </div>
  );
}

Time-Based Revalidation

For data that changes periodically but not constantly, you can use time-based revalidation. This strategy is also known as "stale-while-revalidate".

You can specify a revalidate option within fetch's next property. It tells Next.js how often (in seconds) to re-fetch data in the background, serving cached data in the meantime.

  • next: { revalidate: 60 }: Data will be re-fetched at most every 60 seconds.

Revalidate Option Example

Let's say you have a blog post that updates every few minutes. You can use revalidate to keep it fresh without hitting the API on every single request.

async function getBlogPost(slug) {
  const res = await fetch(`https://api.example.com/posts/${slug}`, {
    next: { revalidate: 3600 } // Revalidate every hour
  });
  if (!res.ok) {
    throw new Error('Failed to fetch blog post');
  }
  return res.json();
}

export default async function BlogPostPage({ params }) {
  const post = await getBlogPost(params.slug);
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
}

On-Demand Revalidation

What if you want to update cached data immediately after a change, like when a user publishes a new post? This is where on-demand revalidation comes in.

Next.js provides two functions for this:

  • revalidatePath('/path'): Invalidates the cache for a specific path.
  • revalidateTag('tag'): Invalidates the cache for all fetches associated with a specific tag.

These are typically used in Server Actions or API Routes after a data mutation.

Using `revalidateTag`

To use revalidateTag, you first need to tag your fetch requests. Then, from a Server Action or API Route, you can trigger a revalidation for that tag.

This allows fine-grained control over your cache, only clearing what's necessary when data actually changes.

async function getProducts() {
  const res = await fetch('https://api.example.com/products', {
    next: { tags: ['products'] } // Tag this fetch request
  });
  if (!res.ok) {
    throw new Error('Failed to fetch products');
  }
  return res.json();
}

// In a Server Action or API Route after adding/updating a product:
// import { revalidateTag } from 'next/cache';
// revalidateTag('products'); // Invalidate all fetches tagged 'products'

export default async function ProductsPage() {
  const products = await getProducts();
  return (
    <div>
      <h1>Our Products</h1>
      <ul>
        {products.map(product => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    </div>
  );
}

Choosing the Right Strategy

Selecting the best caching strategy depends on your data's volatility:

  • cache: 'no-store': For highly dynamic, real-time, or sensitive data that must always be fresh.
  • next: { revalidate: N }: For data that updates periodically (e.g., news articles, blog posts) where some staleness is acceptable.
  • revalidatePath / revalidateTag: For data that changes unpredictably, often due to user actions (e.g., comments, e-commerce inventory), requiring immediate updates after mutation.

Caching Strategy Check

You are building a social media feed where posts are created and updated frequently. You want to ensure users see the latest posts without excessive API calls. Which caching strategy is most suitable for fetching the main feed?

Recap: Server-Side Caching

We've explored key server-side caching strategies in Next.js using the fetch API:

  • Default Caching: fetch uses 'force-cache' by default.
  • Disabling Cache: Use cache: 'no-store' for always-fresh data.
  • Time-Based Revalidation: Use next: { revalidate: N } for stale-while-revalidate.
  • On-Demand Revalidation: Use revalidatePath() or revalidateTag() in Server Actions/API Routes for immediate cache updates.

Mastering these techniques allows you to build highly performant and responsive Next.js applications!

Często zadawane pytania

Czy lekcja „Strategie buforowania po stronie serwera” jest bezpłatna?

Tak — pełny tekst „Strategie buforowania po stronie serwera” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Next.js 15 Fullstack Web Apps, przejdź na CoddyKit PRO. Kurs Next.js 15 Fullstack Web Apps zawiera 4 lekcji w sumie.

Co nauczysz się w „Strategie buforowania po stronie serwera”?

Naucz się buforować dane na serwerze za pomocą opcji `fetch` i ponownej walidacji w celu poprawy wydajności. Ćwiczysz Next.js 15 Fullstack Web Apps z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Next.js 15 Fullstack Web Apps?

Nie wymagamy żadnego doświadczenia. Next.js 15 Fullstack Web Apps w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Strategie buforowania po stronie serwera”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Next.js 15 Fullstack Web Apps?

Tak. Każda lekcja Next.js 15 Fullstack Web Apps zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. React Query do obsługi stanu serwera
  2. Stan po stronie klienta z Zustand/Jotai
  3. Strategie buforowania po stronie serwera
  4. Optymistyczne aktualizacje i unieważnianie pamięci podręcznej
← Powrót do Next.js 15 Fullstack Web Apps