Use Cases

Panduan Lengkap Konfigurasi CORS dengan Claude Code

Pelajari tentang panduan lengkap konfigurasi CORS menggunakan Claude Code. Dilengkapi tips praktis dan contoh kode.

Implementasi Konfigurasi CORS yang Benar dengan Claude Code

CORS (Cross-Origin Resource Sharing) adalah mekanisme yang mengontrol komunikasi aman antar origin yang berbeda. Kesalahan konfigurasi bisa menyebabkan risiko keamanan atau malfungsi. Dengan Claude Code, kamu bisa mengimplementasikan konfigurasi CORS yang sesuai kebutuhan secara akurat.

Konsep Dasar CORS

Alur Preflight Request

> Jelaskan mekanisme preflight request CORS.
> Sertakan juga sequence diagram.

Browser mengirim preflight request dengan method OPTIONS untuk “request yang tidak sederhana” guna memastikan izin dari server. Ini berlaku untuk custom header, POST request berformat JSON, dan sebagainya.

Konfigurasi di Express.js

Konfigurasi CORS per Environment

> Buatkan konfigurasi CORS untuk Express.js.
> Persyaratan:
> - Produksi hanya izinkan origin tertentu
> - Development izinkan localhost
> - Dukung request dengan autentikasi
> - Preflight cache
// src/middleware/cors.ts
import cors from 'cors';

const allowedOrigins: Record<string, string[]> = {
  production: [
    'https://myapp.example.com',
    'https://admin.example.com',
  ],
  development: [
    'http://localhost:3000',
    'http://localhost:5173',
  ],
};

export const corsMiddleware = cors({
  origin: (origin, callback) => {
    const env = process.env.NODE_ENV || 'development';
    const origins = allowedOrigins[env] || allowedOrigins.development;

    // Izinkan komunikasi antar server (tanpa origin)
    if (!origin) return callback(null, true);

    if (origins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error(`CORS: ${origin} tidak diizinkan`));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Request-ID'],
  exposedHeaders: ['X-Total-Count', 'X-Request-ID'],
  maxAge: 86400, // Preflight cache: 24 jam
});

Konfigurasi di Next.js

// next.config.js
const nextConfig = {
  async headers() {
    return [
      {
        source: '/api/:path*',
        headers: [
          { key: 'Access-Control-Allow-Origin', value: 'https://myapp.example.com' },
          { key: 'Access-Control-Allow-Methods', value: 'GET,POST,PUT,DELETE' },
          { key: 'Access-Control-Allow-Headers', value: 'Content-Type,Authorization' },
          { key: 'Access-Control-Allow-Credentials', value: 'true' },
          { key: 'Access-Control-Max-Age', value: '86400' },
        ],
      },
    ];
  },
};

Konfigurasi CORS di Nginx/CDN

> Tambahkan konfigurasi CORS di reverse proxy Nginx.
location /api/ {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' $http_origin;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Max-Age' 86400;
        return 204;
    }

    add_header 'Access-Control-Allow-Origin' $http_origin always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;

    proxy_pass http://backend;
}

Troubleshooting

Error Umum dan Solusinya

Dengan menempelkan error konsol browser ke Claude Code, penyebab dan cara perbaikannya langsung diberitahukan.

Contoh error:

Access to XMLHttpRequest at 'https://api.example.com/data' from origin
'https://myapp.com' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.

Penyebab umum:

  • Header CORS belum dikonfigurasi di sisi server
  • Menggunakan Access-Control-Allow-Origin: * saat credentials: true (perlu menentukan origin spesifik)
  • Tidak menangani method OPTIONS untuk preflight request

Catatan Keamanan

Access-Control-Allow-Origin: * hanya boleh digunakan untuk API publik yang tidak memerlukan autentikasi. Untuk request dengan autentikasi, pastikan menentukan origin spesifik dan mengkombinasikannya dengan credentials: true.

Summary

Dengan Claude Code, kamu bisa mengimplementasikan konfigurasi CORS yang sesuai environment secara akurat dan mengefisienkan troubleshooting. Lihat juga Pengaturan Header Keamanan Web dan Panduan Pengembangan API sebagai referensi.

Untuk detail CORS, lihat MDN Web Docs - CORS.

#Claude Code #CORS #security #API #web development