Next.js Data Fetching outlines how Server Components execute database queries and API requests directly on the server, using extended fetch caching options.
In App Router, data fetching takes place directly inside async Server Components without client-side hooks like useEffect.
flowchart LR
A["Server Component"] --> B["Extended fetch() API"]
B --> C{"Cache Strategy?"}
C -- "force-cache" --> D["Serve Cached Response"]
C -- "no-store" --> E["Fetch Live Data Every Request"]
C -- "revalidate: 60" --> F["Serve Cached Until Stale (60s)"]
Server Components can be marked as async functions to await data fetches directly:
// app/users/page.tsx
interface User {
id: number;
name: string;
email: string;
}
export default async function UsersPage() {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const users: User[] = await res.json();
return (
<div className="p-6">
<h1 className="text-2xl font-bold mb-4">User Directory</h1>
<ul className="divide-y divide-gray-200">
{users.map((user) => (
<li key={user.id} className="py-3">
<p className="font-semibold">{user.name}</p>
<p className="text-sm text-gray-500">{user.email}</p>
</li>
))}
</ul>
</div>
);
}
Next.js extends the native JavaScript fetch API to provide per-request caching control:
// 1. Force Cache (Default SSG Behavior)
fetch('https://api.example.com/data', { cache: 'force-cache' });
// 2. Dynamic Fetch (No Cache / SSR Behavior)
fetch('https://api.example.com/data', { cache: 'no-store' });
// 3. Time-Based Revalidation (ISR Behavior)
fetch('https://api.example.com/data', { next: { revalidate: 3600 } }); // Revalidate hourly
You can clear cached data instantly upon dynamic changes using revalidatePath or revalidateTag:
// app/actions.ts
'use server';
import { revalidatePath, revalidateTag } from 'next/cache';
export async function refreshProductCatalog() {
// Purge cache for a specific route path
revalidatePath('/products');
// Or purge cache by tag
revalidateTag('product-list');
}
Data fetching in Next.js Server Components simplifies data flows. Integrated caching and revalidation controls deliver optimal performance for static and dynamic data alike.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.