What is CORS (Cross-Origin Resource Sharing)?
TL;DR
Security mechanism allowing web applications to make requests to domains other than their own origin.
Cross-Origin Resource Sharing (CORS) is a security mechanism that allows web applications to request resources from different domains. By default, browsers block cross-origin requests for security. CORS headers enable controlled access in Frontend Accelerator.
CORS in API Routes:
export async function GET(request: Request) {
return new Response(JSON.stringify(data), {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
});
}
CORS Headers:
- Access-Control-Allow-Origin: Which domains can access
- Access-Control-Allow-Methods: Allowed HTTP methods
- Access-Control-Allow-Headers: Allowed request headers
- Access-Control-Allow-Credentials: Allow cookies/auth
Common CORS Issues:
- Preflight requests: OPTIONS requests sent before actual request
- Credentials: Cookies require specific CORS configuration
- Wildcard limitations: Cannot use * with credentials
Key Benefits:
- Controlled access: Specify which domains can access your API
- Security: prevents unauthorized cross-origin requests
- Flexibility: enable API consumption from multiple frontends
AI-Friendly: CORS follows standard HTTP header patterns that AI can implement correctly. AI can generate appropriate CORS configurations, handle preflight requests, configure security policies, and troubleshoot common CORS errors effectively.