Server Componentsではasync/awaitで直接データ取得ができる。fetch APIは自動的にキャッシュされ、revalidateで再検証間隔を設定できる。
// Server Component でのデータ取得
async function ProductList() {
// Next.js の拡張fetch: 自動キャッシュ
const products = await fetch('https://api.example.com/products', {
next: { revalidate: 3600 }, // 1時間ごとに再検証 (ISR)
}).then(r => r.json());
return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}
// キャッシュなし(常に最新: SSR相当)
const data = await fetch(url, { cache: 'no-store' });
// 並列データ取得
async function Dashboard() {
const [user, stats] = await Promise.all([
fetch('/api/user').then(r => r.json()),
fetch('/api/stats').then(r => r.json()),
]);
return <div>...</div>;
}
// route.ts: API Routeの定義
// app/api/users/route.ts
export async function GET(request: Request) {
const users = await db.users.findAll();
return Response.json(users);
}
export async function POST(request: Request) {
const body = await request.json();
const user = await db.users.create(body);
return Response.json(user, { status: 201 });
}Server Componentsではコンポーネントツリー内の複数のfetchで同じURLを呼んでも、Reactが自動的に重複排除(dedup)する。