Next.js Data Fetching
Rules
- Fetch in Server Components with async/await. Don't use
useEffect for initial data.
fetch() is cached by default in App Router unless { cache: 'no-store' } or next: { revalidate } says otherwise. Know which you want.
- Parallelize independent requests with
Promise.all. Sequence only when dependent.
- Wrap slow sections in
<Suspense fallback> + loading.tsx for streaming.
- Use
next: { tags: ['posts'] } + revalidateTag('posts') for on-demand invalidation.
- Client-side fetching (SWR/React Query) only for interactive/filtered UI — not for first paint.
Patterns
async function getPosts() {
const res = await fetch('https://api.example.com/posts', {
next: { revalidate: 60 },
});
if (!res.ok) throw new Error('Failed to fetch posts');
return res.json();
}
async function getInbox(userId: string) {
const res = await fetch(`https://api.example.com/inbox/${userId}`, {
cache: 'no-store',
});
return res.json();
}
export default async function Dashboard() {
const [user, posts] = await Promise.all([getUser(), getPosts()]);
return <View user={user} posts={posts} />;
}
import { Suspense } from 'react';
export default function Page() {
return (
<div>
<FastHeader />
<Suspense fallback={<CommentsSkeleton />}>
<SlowComments />
</Suspense>
</div>
);
}
import { revalidateTag } from 'next/cache';
export async function POST(req: Request) {
const { tag, secret } = await req.json();
if (secret !== process.env.REVALIDATE_SECRET)
return Response.json({ ok: false }, { status: 401 });
revalidateTag(tag);
return Response.json({ ok: true });
}
Checklist