5 min read
ā¢Question 17 of 47mediumHow does data fetching work in Next.js?
Fetching data in Server and Client Components.
What You'll Learn
- Server-side fetching
- Caching strategies
- Revalidation
Server Component Fetching
code.txtTSX
// Fetch in Server Component
export default async function Page() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return <div>{data.title}</div>;
}Caching Options
code.txtTSX
// Cached indefinitely (default)
fetch('https://api.example.com/data');
// No caching
fetch('https://api.example.com/data', { cache: 'no-store' });
// Revalidate after 60 seconds
fetch('https://api.example.com/data', {
next: { revalidate: 60 }
});Page-Level Revalidation
code.txtTSX
// Revalidate entire page every 60 seconds
export const revalidate = 60;
// Never cache
export const dynamic = 'force-dynamic';Parallel Fetching
code.txtTSX
export default async function Page() {
// ā
Parallel - both start immediately
const [users, posts] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
]);
return <div>...</div>;
}Sequential Fetching
code.txtTSX
export default async function Page() {
// Waterfall - posts waits for user
const user = await getUser();
const posts = await getPosts(user.id);
return <div>...</div>;
}