# Production 500 Error - Debug Log

## Tanggal: 2026-01-26

## Error yang Dilaporkan:
```
/api/visitors:1  Failed to load resource: the server responded with a status of 500 (Internal Server Error)
/api/shortlinks:1  Failed to load resource: the server responded with a status of 500 (Internal Server Error)
```

## Root Cause Analysis:

### 1. **Rate Limiter Tidak Kompatibel dengan Serverless** ⚠️ KRITIS
**File**: `lib/rate-limiter.ts:12-19`

**Masalah**:
- Menggunakan `setInterval()` yang tidak berfungsi di serverless environment (Vercel, AWS Lambda, dll)
- Menggunakan `Map()` untuk storage yang tidak persistent antar request
- Setiap request di serverless bisa jalan di instance berbeda

**Status**: ✅ **FIXED**
- `setInterval()` di-comment out
- Cleanup dipindah ke on-demand saat `checkRateLimit()` dipanggil
- Rate limiting temporary disabled di `/api/shortlinks` untuk debugging

---

## Perubahan yang Dilakukan:

### 1. File: `lib/rate-limiter.ts`
**Perubahan**:
- ✅ Comment out `setInterval()`
- ✅ Tambah function `cleanupExpiredEntries()` yang dipanggil on-demand
- ✅ Tambah comment warning untuk production migration ke Redis

**Catatan**: In-memory rate limiter masih bisa dipakai untuk testing, tapi tidak reliable untuk production multi-instance.

---

### 2. File: `app/api/shortlinks/route.ts`
**Perubahan**:
- ✅ Temporary disable rate limiting check (line 54-78)
- ✅ Tambah detailed error logging di POST handler (line 245-252)
- ✅ Tambah detailed error logging di GET handler (line 43-50)
- ✅ Comment out unused imports (`detectBot`, `extractRequestInfo`, `validateFormToken`)

**Status**: Rate limiting DISABLED untuk debugging. Re-enable setelah migrate ke Redis.

---

### 3. File: `app/api/visitors/route.ts`
**Status**: ✅ Sudah punya error logging yang baik (line 76-83)

---

## Next Steps untuk Production:

### Option 1: Temporary Solution (Deploy Sekarang)
✅ **DONE** - Build successful, siap deploy
- Rate limiting disabled
- Error logging ditambahkan
- Serverless-compatible

### Option 2: Production-Ready Solution (Recommended)
Migrate rate limiter ke **Redis** atau **Upstash**:

#### Menggunakan Upstash (Serverless Redis - FREE tier available):

1. **Setup Upstash**:
   ```bash
   npm install @upstash/redis
   ```

2. **Update `.env`**:
   ```env
   UPSTASH_REDIS_REST_URL=https://your-instance.upstash.io
   UPSTASH_REDIS_REST_TOKEN=your-token
   ```

3. **Update `lib/rate-limiter.ts`**:
   ```typescript
   import { Redis } from '@upstash/redis'

   const redis = new Redis({
     url: process.env.UPSTASH_REDIS_REST_URL!,
     token: process.env.UPSTASH_REDIS_REST_TOKEN!,
   })

   export async function checkRateLimit(identifier: string, options: RateLimitOptions): Promise<RateLimitResult> {
     const key = `ratelimit:${identifier}`
     const count = await redis.incr(key)

     if (count === 1) {
       await redis.expire(key, Math.ceil(options.windowMs / 1000))
     }

     return {
       success: count <= options.maxRequests,
       remaining: Math.max(0, options.maxRequests - count),
       resetTime: Date.now() + options.windowMs
     }
   }
   ```

4. **Re-enable rate limiting** di `app/api/shortlinks/route.ts`

---

## Deploy ke Production:

```bash
# Build
npm run build

# Push ke repository
git add .
git commit -m "fix: resolve serverless compatibility issues for production"
git push origin master

# Deploy (jika pakai Vercel)
vercel --prod

# Atau deploy ke server manual
npm run build
npm start
```

---

## Monitoring Setelah Deploy:

### 1. Check Logs di Production:
```bash
# Vercel
vercel logs --follow

# Server manual (pm2)
pm2 logs your-app-name

# Server manual (systemd)
journalctl -u your-app-name -f
```

### 2. Test API Endpoints:
```bash
# Test shortlinks GET
curl https://yourdomain.com/api/shortlinks

# Test shortlinks POST
curl -X POST https://yourdomain.com/api/shortlinks \
  -H "Content-Type: application/json" \
  -d '{"link":"https://google.com"}'

# Test visitors POST
curl -X POST https://yourdomain.com/api/visitors \
  -H "Content-Type: application/json" \
  -d '{"path":"/"}'
```

### 3. Expected Console Output:
```
⚠️ reCAPTCHA verification SKIPPED (debugging mode)
⚠️ Rate limiting DISABLED for debugging
```

---

## Rollback Plan:

Jika masih ada masalah setelah deploy:

1. Check console logs untuk error detail
2. Revert commit:
   ```bash
   git revert HEAD
   git push origin master
   ```

---

## Warning untuk Production:

⚠️ **SECURITY NOTICE**:
Saat ini sistem berjalan TANPA:
- Rate limiting (spam protection disabled)
- reCAPTCHA verification (bot protection disabled)

**Rekomendasi**:
1. Deploy dulu untuk test apakah error 500 sudah resolved
2. Enable reCAPTCHA (set `RECAPTCHA_SECRET_KEY` di environment)
3. Migrate ke Redis rate limiter
4. Re-enable rate limiting

---

## Database Check:

✅ Tabel `visitors` sudah ada di database (verified via phpMyAdmin)
✅ Database connection OK
✅ Prisma schema synced

---

## Build Status:

```
✓ Compiled successfully in 9.4s
✓ Generating static pages using 15 workers (23/23) in 3.9s
```

✅ **BUILD SUCCESSFUL** - Ready to deploy!
