Search code examples
aws-lambdacorsaws-api-gatewayamazon-cloudfrontserverless

dynamic Access-Control-Allow-Origin header serverless


I have configured a serverless function as below

id:
  handler: id.get
  events:
    - http:
        path: id
        method: get
        cors:
          origin: ""
          headers:
            - Content-Type
            - X-Amz-Date
            - Authorization
            - X-Api-Key
            - X-Amz-Security-Token
            - x-access-token
          allowCredentials: true

Code in my handler function is as below

let headers = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': event.headers.Origin ? event.headers.Origin : event.headers.origin,
  'Access-Control-Allow-Credentials': true
}
callback(null, {
  "isBase64Encoded": false,
  "statusCode": 200,
  "headers": headers,
  "body": JSON.stringify(body),
  "multiValueHeaders": multiValueHeaders
})

I am getting response to OPTIONS request as

access-control-allow-origin: *
access-control-allow-credentials: true

Due to that I am getting the below error

Access to XMLHttpRequest at 'https://example.com/dev/id' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

I want the Access-Control-Allow-Origin should be dynamic(origin of the request), How can I fix the issue?


Solution

  • I have created a new method options with the below code

    module.exports.options = async (event, context, callback) => {
      const origin = event.headers.Origin || event.headers.origin;
      context.succeed({
        headers: {
          "Access-Control-Allow-Headers": "Accept,Accept-Language,Content-Language,Content-Type,Authorization,x-correlation-id,x-access-token",
          "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS",
          "Access-Control-Allow-Origin": origin ? origin : '*',
          "Access-Control-Allow-Credentials": true
        },
        statusCode: 204
      });
    };
    

    serverless.yml

    options:
      handler: id.options
      events:
        - http:
            path: id
            method: options