Next.js
Beginner
1 min read
Fetching Data in Server Components
Example
// app/dashboard/page.tsx
// Parallel data fetching with Promise.all
async function getUserData(userId: string) {
const res = await fetch(
`https://api.example.com/users/${userId}`,
{ next: { revalidate: 300 } }, // cache for 5 minutes
);
if (!res.ok) throw new Error('Failed to fetch user');
return res.json();
}
async function getUserPosts(userId: string) {
const res = await fetch(
`https://api.example.com/users/${userId}/posts`,
{ cache: 'no-store' }, // always fresh
);
if (!res.ok) throw new Error('Failed to fetch posts');
return res.json();
}
export default async function DashboardPage({
params,
}: {
params: { userId: string };
}) {
// Fetch in parallel — not sequential
const [user, posts] = await Promise.all([
getUserData(params.userId),
getUserPosts(params.userId),
]);
return (
<div>
<h1>Hello, {user.name}</h1>
<ul>
{posts.map((post: { id: string; title: string }) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}