amazon-web-serviceslambdaheaderserverless

Serverless AWS Access-Control-Allow-Headers in preflight response


For some reasom this error appears from nowhere:

has been blocked by CORS policy: Request header field x-company-id is not allowed by Access-Control-Allow-Headers in preflight response.

Here is my serverless.yml lambda function:

  healthPlan:
    handler: src/handlers/health-plan.healthPlanHandler
    events:
      - http:
          path: /health-plan
          method: get
          cors:
            origin: ${self:custom.allowed-origin}
            allowCredentials: ${self:custom.allow-credentials}
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
              - X-Company-Id
              - x-company-id
          authorizer:
            authorizerId: ${cf:auth-service-${self:provider.stage}.ApiAuthorizer}
            type: TOKEN

I'm new to serverless. Could someone give me advice or the answer for current situation? Where should I look? Thanks a lot for help!


Solution

  • Firstly, are you sure you need x-company-id? I see you have also X-Company-Id, which I'm guessing might be the actual header AWS expects?

    Likely x-company-id is being treated as a custom header. I had this same CORS issue with Serverless and AWS when trying to pass actual custom headers to my API.

    My issue was resolved by adding a resources section to serverless.yml to include CORS headers in API Gateway-level error responses and including CORS headers in the normal responses of my lambda handler.

    I found the instructions for performing these 2 steps here.

    Note that, instead of including each header explicitly in the access-control-allow-headers field, you can also just whitelist all headers with * if this is not a security concern.