Stop Tebak Kode, Cara Mengatasi Typeerror Node Js dari Stack Trace

cara mengatasi typeerror node js mulai dari stack trace, bukan menebak baris kode. Cari nama file dan nomor baris pertama yang mengarah ke kode proyek Anda, lalu periksa nilai yang undefined atau bertipe salah tepat sebelum baris itu crash.

TypeError berarti kode berjalan, tapi operasi memakai tipe yang salah. Variabel ada, proses tidak berhenti saat start, lalu gagal saat diakses sebagai objek, dipanggil sebagai fungsi, atau di-loop.

Penyebab Umum TypeError di Node.js

Tiga pesan ini paling sering muncul dan mekanismenya berbeda:

  • Cannot read properties of undefined: Anda mengakses properti dari nilai yang belum ada. Umum di req.body Express tanpa express.json(), hasil query database kosong, atau lupa await.
  • X is not a function: Nama fungsi salah import, beda CommonJS dan ES Module, atau variabel tertimpa nilai non-fungsi.
  • X is not iterable: Kode memakai for…of atau spread pada nilai yang bukan array. Biasanya API mengembalikan objek, null, atau string tunggal.

Stack trace Node.js membaca dari atas ke bawah. Baris pertama berisi pesan error, baris berikutnya berisi lokasi. Abaikan baris node:internal dan fokus ke /src, /routes, atau /controllers milik Anda.

Tabel Diagnosa Cepat TypeError

Pesan Error Penyebab Fokus Perbaikan
Cannot read properties of undefined Objek induk null atau belum siap Cek await, req.body, hasil query
undefined is not a function Import salah atau fungsi tertimpa Cek require, import, dan nama export
Result is not iterable Data bukan array Validasi Array.isArray sebelum loop

Cara Memperbaiki TypeError Langkah demi Langkah

  1. Reproduksi error dengan input sama. Catat endpoint, body request, dan urutan pemanggilan yang memicu crash.
  2. Cek tipe dan isi variabel. Tambahkan log sementara tepat sebelum baris error untuk melihat nilai sebenarnya.
  3. Perbaiki akses objek. Gunakan optional chaining dan nilai default hanya setelah penyebab null ditemukan.
  4. Tambah validasi di batas input. Validasi body Express, parameter route, dan hasil database sebelum dipakai lebih jauh.
// CommonJS
const user = result.rows[0];
if (!user) {
  return res.status(404).json({ message: 'User tidak ditemukan' });
}
console.log(typeof user, user);
res.json({ name: user.name });
// ES Module
const town = data?.address?.city ?? 'Tidak diketahui';
if (!Array.isArray(items)) {
  throw new TypeError('items harus berupa array');
}
for (const item of items) {
  console.log(item.id);
}
  • Validasi req.body Express: pastikan app.use(express.json()) dipasang sebelum route, lalu cek field wajib satu per satu.
  • Null check database: hasil SELECT bisa kosong, hasil Mongoose bisa null. Tangani sebelum membaca propertinya.
  • Gunakan try…catch di fungsi async Express agar rejection tidak menjadi crash tak tertangani.

FAQ

Kenapa TypeError hanya muncul saat runtime?

JavaScript tidak memeriksa tipe saat file dimuat, sehingga kesalahan baru terlihat ketika baris tersebut dieksekusi dengan data nyata.

Apakah optional chaining memperbaiki semua TypeError?

Tidak. Operator itu mencegah crash, tapi data kosong tetap perlu ditangani dengan validasi dan respons yang benar.

Kapan harus cek package.json type module?

Periksa saat error berkaitan require, import, exports, atau __dirname, karena CommonJS dan ES Module memakai sintaks berbeda.