Let’s see the way you arrange CORS utilizing a Lambda Proxy API and AWS SAM. Heads up! This information may also assist repair a CORS error that fails within the browser however works in CURL.
About CORS
Cross-Origin Useful resource Sharing (CORS) is a method to inform browsers which area, HTTP strategies, and HTTP header(s) to belief. Due to this fact, this mechanism permits a server to point any origins (area, scheme, or port) (and extra) apart from its personal from which a browser ought to allow loading assets.
This header-based mechanism depends on pre-flight requests made by shoppers earlier than truly sending the meant request off. The pre-flight request sends a request to the OPTIONS technique of the API to attain this.
When do you want CORS?
You may group CORS requests into two sorts: easy requests and non-simple requests.
A CORS request is easy if all the next are true:
- The API Solely accepts GET, HEAD, and POST requests.
- The request consists of the Origin header for the POST technique request.
- The request payload content material kind is: textual content/plain, multipart/form-data, or utility/x-www-form-urlencoded.
- The API useful resource doesn’t comprise customized headers.
- And lastly, any extra necessities are listed within the Mozilla CORS documentation.
All different CORS requests are non-simple requests and require your API to allow CORS assist.
About AWS SAM
The Serverless Software Mannequin (SAM) is a framework the place you’ll be able to construct serverless purposes. It offers shorthand syntax for outlining features, APIs, and extra in a single doc utilizing YAML – with out having any setup or upkeep trouble!
Let’s Get Began!
First, it’s essential arrange the CORS config within the globals part of your AWS SAM template.
Consequently, your globals part ought to appear to be this:
AWSTemplateFormatVersion: '2010-09-09'
Remodel: AWS::Serverless-2016-10-31
Description: CORS through Globals
Globals:
Api:
Cors:
AllowOrigin: "'*'"
AllowHeaders: "*"
AllowMethods: "'*'"
Assets:
MyFunction:
...
Subsequent, you want the CORS config to REST API useful resource.
This setting means your API part ought to appear to be this:
AWSTemplateFormatVersion: '2010-09-09'
Remodel: AWS::Serverless-2016-10-31
Description: CORS through useful resource
Assets:
MyRestApi:
Sort: AWS::Serverless::Api
Properties:
StageName: Prod
Cors:
AllowOrigin: "'*'"
AllowHeaders: "'*'"
AllowMethods: "'*'"
...
Lastly, you should add the CORS config to the REST API response.
Due to this fact, your Lambda handler ought to reply with one thing like this:
{
"statusCode": status_code,
"headers": {
"Entry-Management-Enable-Origin": "*",
"Entry-Management-Enable-Headers": "*",
"Entry-Management-Enable-Strategies": "*",
},
"physique": json_str,
}
Watch out for The ApiKeyRequired Parameter!
In some instances, the ApiKeyRequired could cause issues for JavaScript frameworks. For instance, setting this parameter within the “AWS::Serverless::Api” part allows the “x-api-key” header for preflight checks. Nevertheless, the JavaScript framework could not at all times embrace the “x-api-key” within the pre-flight checks.
The instance beneath units the ApiKeyRequired parameter within the API Useful resource block:
AWSTemplateFormatVersion: '2010-09-09'
Remodel: AWS::Serverless-2016-10-31
Description: CORS through useful resource
Assets:
MyRestApi:
Sort: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
ApiKeyRequired: true # units for all strategies
Cors:
AllowOrigin: "'*'"
AllowHeaders: "'*'"
AllowMethods: "'*'"
...
Instance output in API Gateway:

You may keep away from this error by setting ApiKeyRequired to false after which making use of this setting manually on the “AWS::Serverless::Operate” useful resource.
Consequently, your Operate useful resource ought to appear to be this:
ApiPostCustomer:
Sort: "AWS::Serverless::Operate"
Properties:
...
Occasions:
apiPostCustomerEvent:
Sort: "Api"
Properties:
...
Auth:
ApiKeyRequired: true
...
Because of this, your API Gateway will appear to be this:

Greatest Observe Issues
The examples talked about above set the access-control-allow-origin, access-control-allow-headers, and access-control-allow-methods to “*” or any. Nevertheless, it might be greatest by no means to permit “any” as it is a horrible safety follow. Thus, it’s essential be extra particular and keep away from “any”.
Watch out when utilizing * as this might enable the browser entry to unintended assets.
How will you take a look at the CORS configuration?
CURL is a superb device to check your CORS configuration:
curl --verbose --location --request ''
However, in fact, you should change the tactic and the URL parameters accordingly.
For instance, right here it’s essential:
- Set the tactic to “OPTIONS” or the meant HTTP technique like “GET”.
- URL is the URL of your REST API
You’ll, because of this, see an output like this:
> curl --verbose --location --request OPTIONS 'https://czr4jjjj.execute-api.us-east-1.amazonaws.com/v1/buyer'
* Attempting 3.236.158.2:443...
* TCP_NODELAY set
...
...
* Connection state modified (MAX_CONCURRENT_STREAMS == 128)!
If the ApiKeyRequired parameter have been set on the API useful resource, you’d see a forbidden response:
Wrapping Up
You might have discovered methods to allow CORS when utilizing AWS Lambda Proxy API and AWS SAM. As well as, you could have discovered methods to allow the API Key required parameter for all strategies besides OPTIONS, which might trigger a “forbidden” error. Due to this fact, it’s best to now be capable of entry your API assets by CURL and the browser.
You Might Additionally Be In
Sources: