Buat fungsi komponen jadi async, lalu panggil await fetch() langsung di dalamnya. Pola ini hanya berjalan di Server Component App Router, tanpa useEffect dan tanpa useState.
type Produk = { id: number; nama: string };
async function getProduk() {
const res = await fetch("https://api.example.com/produk");
if (!res.ok) {
throw new Error("Gagal memuat produk");
}
return res.json() as Promise<Produk[]>;
}
export default async function Page() {
const produk = await getProduk();
return (
<ul>
{produk.map((item) => (
<li key={item.id}>{item.nama}</li>
))}
</ul>
);
}
Fetch API Langsung di Fungsi Async Server Component
Server Component berjalan di server, jadi kode fetch tidak terkirim ke browser. Secret seperti API key tetap aman selama tidak memakai prefix NEXT_PUBLIC_.
- Buat file
app/produk/page.tsx. - Ubah komponen menjadi
export default async function Page(). - Buat fungsi
getProduk()terpisah untuk fetch dan parsing JSON. - Cek
response.oksebelumres.json()agar error HTTP terbaca jelas. - Render data langsung dari hasil
await, tanpa state loading manual. - Sediakan
error.tsxdi folder route yang sama untuk menangkap error fetch.
- Jangan memakai
use clienthanya untuk fetch awal halaman. - Jangan memanggil
window,document, ataulocalStoragedi fungsi ini. - Pisahkan tipe data agar respons API mudah divalidasi.
Atur Cache dan Error Handling agar Data Tidak Stale
Next.js bisa menyimpan hasil fetch di server. Pilih perilakunya sesuai seberapa cepat data berubah.
| Opsi | Cocok untuk | Catatan |
|---|---|---|
| Default statis | Katalog dan profil | Bisa stale setelah build |
cache: no-store |
Stok dan harga live | Selalu ambil data baru |
next: revalidate: 60 |
Berita dan daftar harian | Segar tiap 60 detik |
await fetch("https://api.example.com/stok", {
cache: "no-store",
});
await fetch("https://api.example.com/berita", {
next: { revalidate: 60 },
});
Gunakan try catch bila kegagalan API tidak boleh meruntuhkan seluruh halaman.
try {
const res = await fetch("https://api.example.com/produk");
if (!res.ok) return [];
return await res.json();
} catch {
return [];
}
FAQ
Apakah perlu use client untuk fetch di Server Component?
Tidak. Fetch awal cukup memakai Server Component async agar bundle client tetap kecil.
Kapan memakai Route Handler sebagai pengganti fetch langsung?
Pakai Route Handler bila browser perlu memanggil ulang data lewat JavaScript atau bila perlu menyembunyikan kredensial.
Kenapa data fetch tidak berubah setelah API diperbarui?
Hasil lama biasanya masih tersimpan di cache, jadi ubah ke no-store atau atur interval revalidate.