Pola Async untuk Cara Fetch Api di Server Component Next Js

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_.

  1. Buat file app/produk/page.tsx.
  2. Ubah komponen menjadi export default async function Page().
  3. Buat fungsi getProduk() terpisah untuk fetch dan parsing JSON.
  4. Cek response.ok sebelum res.json() agar error HTTP terbaca jelas.
  5. Render data langsung dari hasil await, tanpa state loading manual.
  6. Sediakan error.tsx di folder route yang sama untuk menangkap error fetch.
  • Jangan memakai use client hanya untuk fetch awal halaman.
  • Jangan memanggil window, document, atau localStorage di 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.