🔧 Solving CORS Issues in AWS API Gateway: A Practical Guide
Handling CORS in AWS API Gateway can be tricky, but with the right headers and configuration — whether using REST or HTTP APIs — you can resolve the issue cleanly. Once set up, you’ll unlock seamless.
If you've ever seen this frustrating error in your browser console:
Access to fetch at 'https://api.example.com/accounts/auth/token' from origin 'https://app.example.com' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
You're not alone. Let’s break down what this error means and how to fix it when using AWS API Gateway — whether you're building a serverless backend or exposing microservices via Lambda.
🚨 The Problem: Cross-Origin Request Blocked
Modern browsers enforce a security feature called CORS (Cross-Origin Resource Sharing). If your frontend (e.g.,
https://app.example.com
) tries to call an API hosted on a different domain (e.g.,
https://api.example.com
), the browser will first send a preflight OPTIONS request to check if the server allows it.
If the API response doesn’t include appropriate CORS headers, the browser blocks the request — even if the server responds with 200 OK
.
✅ The Solution: Add CORS Support in API Gateway
Case 1: Using REST API Gateway
Enable the OPTIONS Method for your route:
In the AWS API Gateway Console, go to your resource (
/accounts/auth/token
).If not already there, create an
OPTIONS
method.
Configure the Method Response:
Add the following headers under "Response Headers for 200":
Access-Control-Allow-Origin
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Configure the Integration Response:
Under "Header Mappings" for 200, add:
Access-Control-Allow-Origin: 'https://app.example.com'
Access-Control-Allow-Headers: 'Content-Type,Authorization'
Access-Control-Allow-Methods: 'POST,OPTIONS'
Deploy the API.
Case 2: Using HTTP API Gateway (Recommended for Simplicity)
Go to your HTTP API in the API Gateway console.
Click on the “Routes” tab.
Select your route (e.g.,
/accounts/auth/token
) and choose “Attach CORS configuration”.Set:
Allowed origins:
https://app.example.com
Allowed methods:
OPTIONS
,POST
Allowed headers:
Content-Type
,Authorization
Deploy your changes.
🧩 Bonus: If You’re Using Lambda
Make sure your Lambda function returns CORS headers as part of the response:
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': 'https://app.example.com',
'Access-Control-Allow-Headers': 'Content-Type,Authorization',
'Access-Control-Allow-Methods': 'OPTIONS,POST'
},
body: JSON.stringify({ success: true })
};