Fetching data and streaming
In the App Router, most data fetching happens in Server Components, with plain async/await. No useEffect, no loading state juggling, no extra API layer for reads.
Fetching in a Server Component
// app/blog/page.tsx
type Post = { id: number; title: string };
export default async function BlogPage() {
const res = await fetch('https://api.example.com/posts');
if (!res.ok) throw new Error('Failed to load posts'); // caught by the nearest error.tsx
const posts: Post[] = await res.json();
return (
<ul>
{posts.map((post) => <li key={post.id}>{post.title}</li>)}
</ul>
);
}You can also query a database or ORM directly:
import { db } from '@/lib/db';
export default async function Page() {
const users = await db.user.findMany({ take: 10 });
return <p>{users.length} users</p>;
}Good to know: in Next.js 16,
fetchresults are not cached by default. Each request gets fresh data. You opt into caching explicitly with'use cache'(see the Caching lesson).
Avoid waterfalls: fetch in parallel
Sequential awaits add up. If the requests are independent, start them together:
export default async function Dashboard() {
// ✗ Sequential: total time = user + orders + stats
// const user = await getUser(); const orders = await getOrders(); ...
// ✓ Parallel: total time = the slowest one
const [user, orders, stats] = await Promise.all([getUser(), getOrders(), getStats()]);
return <h1>Hi {user.name}: {orders.length} orders, {stats.visits} visits</h1>;
}Streaming with loading.tsx
Add a loading.tsx next to a page to show an instant loading state while the page's data loads. The layout stays visible and interactive:
// app/blog/loading.tsx
export default function Loading() {
return <p>Loading posts…</p>; // or a skeleton UI
}Behind the scenes, Next.js wraps your page in a React <Suspense> boundary with this as the fallback.
Granular streaming with <Suspense>
Show the fast parts of a page immediately, and stream slow parts in as they finish:
import { Suspense } from 'react';
export default function ProductPage() {
return (
<>
<ProductDetails /> {/* fast: shows immediately */}
<Suspense fallback={<p>Loading reviews…</p>}>
<Reviews /> {/* slow: streams in when ready */}
</Suspense>
<Suspense fallback={<p>Loading recommendations…</p>}>
<Recommendations />
</Suspense>
</>
);
}
async function Reviews() {
const reviews = await getReviews(); // takes 2 seconds
return <ul>{reviews.map((r) => <li key={r.id}>{r.text}</li>)}</ul>;
}Here's the same behaviour simulated in the browser with React's use hook and Suspense:
Meaningful loading states: prefer skeletons that match the final layout over generic spinners, so the page doesn't jump when the content arrives.
Runtime data: cookies, headers and searchParams
APIs that depend on the incoming request make a component render per request. Wrap such components in <Suspense> so the rest of the page can still be pre-rendered:
import { cookies } from 'next/headers';
import { Suspense } from 'react';
async function Greeting() {
const theme = (await cookies()).get('theme')?.value ?? 'light'; // cookies() is async
return <p>Your theme: {theme}</p>;
}
export default function Page() {
return (
<>
<h1>Dashboard</h1>
<Suspense fallback={<p>Loading…</p>}>
<Greeting />
</Suspense>
</>
);
}Client-side fetching (when you need it)
For data that changes constantly while the user is on the page (live search, polling, infinite scroll), fetch in a Client Component with a library like SWR or TanStack Query:
'use client';
import useSWR from 'swr';
const fetcher = (url: string) => fetch(url).then((r) => r.json());
export function Notifications() {
const { data, error, isLoading } = useSWR('/api/notifications', fetcher, { refreshInterval: 5000 });
if (isLoading) return <p>Loading…</p>;
if (error) return <p>Failed to load</p>;
return <p>{data.unread} unread</p>;
}Practice (in your project)
- Build
/posts, which fetches 10 posts fromhttps://jsonplaceholder.typicode.com/postsin a Server Component. - Add a
loading.tsxwith a skeleton list. - On
/posts/[id], fetch the post and its comments in parallel withPromise.all, and stream the comments with<Suspense>.
1.Where is data usually fetched in the App Router?
2.What does wrapping a slow component in <Suspense fallback={...}> do?