This has always annoyed CORS if you want to include multiple Origins.
A common workaround on other systems (e.g. express / nginx, etc.) is:
- check the
Origin header sent by the browser - check it for a white list.
- if it matches, return the incoming
Origin as the Access-Control-Allow-Origin header, otherwise return the placeholder (default start)
This is not possible if you use CORS support with AWS-Gateway support, since mock integration is used, but it is possible if you write your own code to process the OPTIONS request.
The following is an example of code written using lambda proxy integration:
const allowedOrigins = [ "http://example.com", "http://example.com:8080", "https://example.com", "https?://[az]*.?myapp.com", "http://localhost:[0-9]*" ]; exports.handler = (event, context) => { const origin = event.headers.Origin || event.headers.origin; var goodOrigin = false; if (origin) { allowedOrigins.forEach( allowedOrigin => { if (!goodOrigin && origin.match(allowedOrigin)) { goodOrigin = true; } }); } context.succeed({ headers: { "Access-Control-Allow-Headers": "Accept,Accept-Language,Content-Language,Content-Type,Authorization,x-correlation-id", "Access-Control-Expose-Headers": "x-my-header-out", "Access-Control-Allow-Methods": "DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT", "Access-Control-Allow-Origin": goodOrigin ? origin : allowedOrigins[0] }, statusCode: 204 }); };
Save this as a function of lambda. To set this in the API Gateway, add the OPTIONS method, and for Integration Request select the Lambda Function with the Use Lambda Proxy integration .
Of course, the disadvantage of this is that you pay for lambda functions, and calling a lambda function is likely to be an additional 50 ms latency compared to mock integration.