Next.js Data Fetching Explained — Fetching Data in Server and Client
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Next.js Data Fetching Explained. We cover key concepts, practical examples, and best practices to help you master this topic.
Next.js offers multiple data fetching strategies: server components fetch data directly with async/await, route handlers provide API endpoints, and client components fetch with hooks.
What You'll Learn
- Server component data fetching
- Route handlers (API routes)
- Client-side data fetching
- Caching and revalidation
- React Query integration
Why It Matters
Choosing the right data fetching Strategy affects performance, SEO, and user experience. Server fetching is faster and more secure, client fetching enables real-time updates.
// app/posts/page.jsx — Server component fetch
export default async function PostsPage() {
const posts = await fetch("https://api.example.com/posts", {
next: { revalidate: 3600 },
}).then(r => r.json());
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
// app/api/posts/route.js — Route handler
export async function GET() {
const posts = await db.getPosts();
return Response.json(posts);
}
export async function POST(request) {
const body = await request.json();
const post = await db.createPost(body);
return Response.json(post, { status: 201 });
}
// app/posts/client-page.jsx — Client component fetch
"use client";
import useSWR from "swr";
export default function ClientPosts() {
const { data, error, isLoading } = useSWR("/api/posts");
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <ul>{data.map(p => <li key={p.id}>{p.title}</li>)}</ul>;
}
Expected output: Server component pre-renders HTML with data, route handler returns JSON at /api/posts, client component fetches with loading state.
← Previous
Next.js Layouts Explained — Nested and Shared Layouts
Next →
Next.js Static Site Generation (SSG) Explained — Pre-Built Pages
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro