Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to How To Guides
How to Do Data Fetching in Next.js

How to Do Data Fetching in Next.js

How To Guides2,027 viewsBy Admin
how-todatafetchingnextjs

Advertisement

Data Fetching in the App Router

In the Next.js App Router you fetch data by simply using async/await inside Server Components. The framework handles caching and revalidation for you.

Basic Fetch

export default async function Page() {
  const res = await fetch("https://api.example.com/posts");
  const posts = await res.json();
  return <PostList posts={posts} />;
}

Controlling the Cache

// Cache forever (static, default)
fetch(url);

// Never cache (always fresh)
fetch(url, { cache: "no-store" });

// Revalidate every 60 seconds (ISR)
fetch(url, { next: { revalidate: 60 } });

Parallel Fetching (Faster)

export default async function Page() {
  const [user, posts] = await Promise.all([
    fetch("/api/user").then(r => r.json()),
    fetch("/api/posts").then(r => r.json()),
  ]);
  return <Profile user={user} posts={posts} />;
}

Fetching in Client Components

"use client";
import useSWR from "swr";

const fetcher = (url) => fetch(url).then(r => r.json());

function Profile() {
  const { data, error, isLoading } = useSWR("/api/user", fetcher);
  if (isLoading) return <p>Loading...</p>;
  return <div>{data.name}</div>;
}

FAQs

Server-side or client-side fetching?

Prefer server-side — it's faster, better for SEO, and keeps secrets safe. Use client fetching (SWR/React Query) for user-specific, frequently-changing data.

How do I revalidate on demand?

Call revalidatePath() or revalidateTag() in a Server Action or route handler. More in our how-to guides.

Advertisement