API Gateway CORS Configuration
You'll learn how to configure Cross-Origin Resource Sharing (CORS) in your API Gateway so browser-based apps can successfully call your APIs.
What is CORS and Why Do You Need It?
Imagine your web app runs at https://myapp.com, but your API lives at https://api.mybackend.com. When your JavaScript tries to fetch data from the API, the browser blocks it by default—this is the same-origin policy, a security feature preventing malicious sites from stealing data.
CORS is the mechanism that tells the browser: "It's okay, this cross-origin request is allowed." Your API Gateway needs to send special HTTP headers back to the browser granting permission.
How CORS Works in API Gateway
When you enable CORS configuration on your API Gateway, it handles the browser's preflight request (an OPTIONS request the browser sends first) and adds necessary response headers like:
Access-Control-Allow-Origin: Which domains can access (e.g.,https://myapp.comor*for all)Access-Control-Allow-Methods: Which HTTP methods are permitted (GET, POST, etc.)Access-Control-Allow-Headers: Which custom headers the browser can send
Configuration Essentials
You typically configure CORS per API resource or globally:
- Allowed Origins: Specify exact domains or use
*(though*prevents credentials from being sent) - Allowed Methods: Match the methods your API supports (GET, POST, PUT, DELETE, etc.)
- Allowed Headers: Include any custom headers like
AuthorizationorContent-Type - Max Age: How long browsers cache preflight responses (in seconds)
Without proper CORS configuration, browser-based clients receive cryptic errors even when authentication and throttling are correctly set up.
Key Takeaway:
CORS configuration in API Gateway enables browser apps to call your APIs by instructing the browser which cross-origin requests are safe—configure allowed origins, methods, and headers to match your client needs.