Search code examples
next.jsaxioscorsaws-api-gatewaypreflight

CORS Pre-flight checks OPTIONS error from AWS Gateway API


I am struggling to resolve a '403' error: '... has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status'

Any advice on how I can debug or what I could be missing is appreciated

Tests conducted thus far:

My lambda function in AWS responds with the correct headers:

  • OPTIONS CURL TEST: CURL Options test

  • Copied failed axios command as CURL (cmd) from chrome dev tools :copy failed cmd as curl from dev tols - (this does not work in command line, curl responds with: 'curl: (3) URL using bad/illegal format or missing URL' )

  • Copied failed axios command as fetch from chrome dev tools: copy bad command as fetch

  • Online CORS Validator:enter image description here

  • And postman response to prove without cors, the functions works:enter image description here

Other info:

  • I have validated the url, x-api-key etc many times, and tried different configurations of the axios request, all result in the same response, see the following image of the axios request enter image description here

  • A few images from APIGateway showing the requests and integrations:api gateway console image 1api gateway
console image 2

OPTIONS request/response in the browser (suggested by Quentin ): browser response 1 browser response 2

My Current lines of reasoning:

  • Maybe there is an additional security setting I need to define in my cloudwatch template?
  • Maybe there is a bug in webpack with next.js / axios 0.27.2 / node 16.14.0 . - I have found a near- identical response mentioned HERE

Solution

  • The 403 error is due to the OPTIONS response x-api-key not being expected by the web browser for pre-flight checks

    Once I disabled the global x-api-key required in the cloudformation template via:

    Auth:
        ApiKeyRequired: false
    

    The result as shown here; on the console depicts OPTIONS -> API Key 'Not Required' Answer

    -The response succeeded!

    In conclusion, api-gateway interferes with the expected preflight process via it's default copnfiguration.
    Be warned!

    There is however a snag outside the scope of this question, in that multiple people have report difficulting enabled ApiKeyRequired for POST and not OPTIONS. This is a cloudformation issue (Please see linked sources below for more details)

    UPDATE:

    In conducting further research, enough people complained March 2022 with this exact problem, a specific flag 'AddApiKeyRequiredToCorsPreflight' was then added.

    Example here

    Discussion Sources: