# 🚨 Memahami eval di JavaScript, Bahayanya, dan Cara Mengatasinya di Vite + React + TS + Hono

## 1\. Apa itu `eval`?

`eval` adalah fungsi bawaan JavaScript yang bisa mengeksekusi string sebagai kode JavaScript.  
Contoh:

```js
const code = "2 + 2";
console.log(eval(code)); // 4
```

Sekilas terlihat praktis, tapi sangat berisiko. `eval` akan membaca string apa adanya lalu menjalankannya. Jika string itu berasal dari input user atau sumber luar, bisa memicu **serangan injeksi kode (XSS)**.

---

## 2\. Kenapa `eval` Berbahaya?

Ada beberapa alasan kenapa `eval` dianggap **insecure**:

1. **XSS (Cross-Site Scripting):**  
    Penyerang bisa menyisipkan script berbahaya yang langsung dieksekusi.  
    Misalnya, `eval("alert(document.cookie)")` → mencuri cookie user.
    
2. **Membuka pintu arbitrary code execution:**  
    Jika ada input tak tervalidasi, attacker bisa jalankan perintah tak diinginkan.
    
3. **Mengganggu keamanan modern (CSP):**  
    Browser modern + CSP (Content Security Policy) default sering **memblok** `eval`, sehingga error muncul:
    
    > *Content Security Policy of your site blocks the use of 'eval' in JavaScript*
    
4. **Lambat & sulit dioptimasi:**  
    Engine JavaScript (seperti V8) tidak bisa mengoptimasi kode `eval`, karena isinya bisa berubah-ubah.
    

---

## 3\. Kenapa Error `eval` Muncul di Vite + React + TypeScript + Hono?

Ketika membangun aplikasi dengan **Vite + React TS**, ada beberapa penyebab umum:

* **Vite dev server**: saat mode development, Vite menggunakan `eval` untuk debugging **source maps** (misalnya `eval-source-map`).
    
* **Library pihak ketiga**: beberapa package lama masih pakai `eval` atau `new Function()`.
    
* **CSP ketat** di server Hono: kamu mungkin mengatur header CSP tanpa `unsafe-eval`.
    

---

## 4\. Cara Mengatasi Error CSP karena `eval`

### 🔹 (1) **Hilangkan pemakaian** `eval`

* Jangan gunakan `eval` atau `new Function()` secara manual.
    
* Ganti `eval("2+2")` → `2+2` langsung.
    
* Ganti `setTimeout("doSomething()", 100)` → `setTimeout(doSomething, 100)`.
    

---

### 🔹 (2) **Pastikan Vite tidak pakai eval di production**

* Secara default, `vite build` menghasilkan bundle **tanpa eval**.
    
* Masalah biasanya hanya di **dev mode**.
    
* Jika error muncul di production, pastikan **mode build benar**:
    
    ```bash
    vite build --mode production
    ```
    
* Periksa `vite.config.ts`, hindari source map berbasis eval:
    
    ```ts
    export default defineConfig({
      build: {
        sourcemap: true, // aman, tidak pakai eval
      }
    })
    ```
    

---

### 🔹 (3) **Atur CSP Header di Hono**

Jika kamu ingin **izin sementara** untuk development (agar error hilang), tambahkan `'unsafe-eval'` di CSP **hanya di dev mode**.

Contoh middleware Hono:

```ts
import { Hono } from 'hono'

const app = new Hono()

app.use('*', async (c, next) => {
  const isDev = process.env.NODE_ENV !== 'production'
  const csp = isDev
    ? "default-src 'self'; script-src 'self' 'unsafe-eval';"
    : "default-src 'self'; script-src 'self';"
  
  c.header('Content-Security-Policy', csp)
  await next()
})

app.get('/', (c) => c.html('<h1>Hello Vite + React + Hono!</h1>'))

export default app
```

⚠️ Catatan: `'unsafe-eval'` **tidak boleh dipakai di production**.

---

### 🔹 (4) **Gunakan Nonce / Hash di CSP (solusi aman)**

Kalau aplikasi butuh inline script tanpa `eval`, gunakan **nonce**:

```ts
app.use('*', async (c, next) => {
  const nonce = crypto.randomUUID()
  c.header('Content-Security-Policy', `script-src 'self' 'nonce-${nonce}';`)
  c.set('csp-nonce', nonce)
  await next()
})
```

Lalu saat render HTML:

```html
<script nonce="THE_NONCE">console.log("aman!")</script>
```

---

### 🔹 (5) **Gunakan Report-Only Mode untuk Debug**

Untuk mengecek pelanggaran tanpa memblokir:

```ts
app.use('*', (c, next) => {
  c.header(
    'Content-Security-Policy-Report-Only',
    "default-src 'self'; script-src 'self'; report-uri /csp-report"
  )
  return next()
})

app.post('/csp-report', async (c) => {
  const report = await c.req.json()
  console.log('CSP Report:', report)
  return c.text('ok')
})
```

---

## 5\. Rekomendasi Praktis untuk Project Vite + React + TS + Hono

1. **Development**:
    
    * Tambahkan sementara `'unsafe-eval'` di CSP untuk mencegah error saat hot-reload.
        
    * Atau gunakan `vite --mode production` jika mau test tanpa eval.
        
2. **Production**:
    
    * Jangan gunakan `'unsafe-eval'`.
        
    * Deploy hasil `vite build`.
        
    * Gunakan CSP yang ketat dengan `script-src 'self'` + nonce/hash.
        
3. **Library check**:
    
    * Selalu audit library dengan `grep "eval("` di `node_modules`.
        
    * Cari alternatif library yang tidak pakai `eval`.
        

---

## 6\. Kesimpulan

* `eval` berbahaya karena membuka celah XSS dan memperlambat performa.
    
* Error `Content Security Policy blocks 'eval'` muncul karena CSP memblokir `eval`.
    
* Di **Vite React TS + Hono**, masalah biasanya muncul di **dev mode** (bukan production).
    
* Solusi:  
    ✅ Jangan pakai `eval` manual.  
    ✅ Pastikan `vite build` untuk production.  
    ✅ Gunakan CSP aman di Hono (nonce/hash), `'unsafe-eval'` hanya untuk development jika terpaksa.
