Obtención de Datos en Next.js
Reglas
- Realiza el fetch en Server Components con async/await. No uses
useEffect para los datos iniciales.
fetch() está cacheado por defecto en App Router a menos que se especifique { cache: 'no-store' } o next: { revalidate }. Conoce cuál quieres usar.
- Paraleliza solicitudes independientes con
Promise.all. Secuencializa solo cuando haya dependencias.
- Envuelve secciones lentas en
<Suspense fallback> + loading.tsx para streaming.
- Usa
next: { tags: ['posts'] } + revalidateTag('posts') para invalidación bajo demanda.
- El fetching del lado del cliente (SWR/React Query) solo para UI interactiva o filtrada, no para la primera pintura.
Patrones
async function getPosts() {
const res = await fetch('https://api.example.com/posts', {
next: { revalidate: 60 },
});
if (!res.ok) throw new Error('Error al obtener los 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 });
}
Lista de Verificación