Files
Retribusi/api/CORS_SETUP_GUIDE.md

5.0 KiB

Panduan Setup CORS untuk API Btekno

Masalah

Browser tidak dapat mengakses API karena CORS (Cross-Origin Resource Sharing) belum dikonfigurasi.

Solusi

Tambahkan CORS handler di AWAL setiap file endpoint PHP:

<?php
// ==================== CORS HANDLER - HARUS DI AWAL ====================
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-API-KEY");
header("Access-Control-Max-Age: 3600");

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}
// ==================== END CORS HANDLER ====================

// Lanjutkan dengan logic endpoint...

Metode 2: CORS Handler di Bootstrap/Autoload

Jika menggunakan framework atau autoloader, tambahkan CORS handler di file bootstrap:

File: bootstrap.php atau index.php

<?php
// CORS Handler
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-API-KEY");
header("Access-Control-Max-Age: 3600");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Lanjutkan dengan routing/autoload...

Metode 3: CORS Handler di .htaccess (Apache)

Jika menggunakan Apache, tambahkan di .htaccess:

# CORS Headers
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-API-KEY"
    Header set Access-Control-Max-Age "3600"
</IfModule>

# Handle OPTIONS request
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>

Metode 4: CORS Handler di Nginx Config

Jika menggunakan Nginx, tambahkan di config:

location / {
    # CORS Headers
    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-API-KEY' always;
    add_header 'Access-Control-Max-Age' '3600' always;
    
    # Handle OPTIONS request
    if ($request_method = 'OPTIONS') {
        return 204;
    }
    
    # Proxy atau serve PHP
    try_files $uri $uri/ /index.php?$query_string;
}

Endpoint yang Perlu CORS Handler

Pastikan semua endpoint berikut memiliki CORS handler:

  1. /health - Health check
  2. /auth/v1/login - Login
  3. /retribusi/v1/dashboard/summary - Dashboard summary
  4. /retribusi/v1/summary/hourly - Hourly summary
  5. /retribusi/v1/dashboard/daily - Daily chart
  6. /retribusi/v1/dashboard/by-category - By category chart
  7. /retribusi/v1/realtime/snapshot - Realtime snapshot
  8. Semua endpoint lainnya

Testing CORS

Test dengan curl:

# Test OPTIONS request (preflight)
curl -X OPTIONS https://api.btekno.cloud/auth/v1/login \
  -H "Origin: http://localhost" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: Content-Type" \
  -v

# Harus return:
# < HTTP/1.1 200 OK
# < Access-Control-Allow-Origin: *
# < Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
# < Access-Control-Allow-Headers: Content-Type, Authorization, X-API-KEY

Test dengan browser:

  1. Buka dashboard/test-connection.html
  2. Klik "Test Health Check"
  3. Buka Developer Tools (F12) → Network tab
  4. Cek apakah request OPTIONS return 200 dengan CORS headers

Troubleshooting

Masalah: Masih error "Failed to fetch"

  • Pastikan CORS handler di AWAL file, sebelum output apapun
  • Pastikan tidak ada output (echo, print, whitespace) sebelum CORS headers
  • Pastikan OPTIONS request return 200, bukan 404 atau 405

Masalah: CORS headers tidak muncul

  • Cek apakah mod_headers enabled (Apache)
  • Cek apakah PHP output buffering tidak mengganggu
  • Cek apakah ada error PHP sebelum headers dikirim

Masalah: Preflight OPTIONS gagal

  • Pastikan server menangani method OPTIONS
  • Pastikan return 200 untuk OPTIONS request
  • Jangan proses logic endpoint untuk OPTIONS request

Security Note

⚠️ Untuk Production:

  • Ganti Access-Control-Allow-Origin: * dengan domain spesifik:
    header("Access-Control-Allow-Origin: https://yourdomain.com");
    
  • Atau gunakan whitelist:
    $allowedOrigins = ['https://yourdomain.com', 'https://app.yourdomain.com'];
    $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
    if (in_array($origin, $allowedOrigins)) {
        header("Access-Control-Allow-Origin: $origin");
    }
    

Quick Fix

Copy file cors-handler.php dan include di setiap endpoint:

<?php
require_once __DIR__ . '/cors-handler.php';

// Endpoint logic di sini...