Enable CORS in AWS API Gateway + Lambda proxy integration with AWS CDK
- Published on
- Authors
- Name
- Binh Bui
- @bvbinh
As a web developer, I have to deal with CORS issues a lot. CORS is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.
In this article, We will learn what CORS is and how to enable CORS API with AWS CDK.
What is CORS?
CORS stands for Cross-Origin Resource Sharing
. It is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos. Certain "cross-domain" requests, notably Ajax requests, are forbidden by default by the same-origin security policy. CORS defines a way in which the browser and the server can interact to determine whether or not it is safe to allow the cross-origin request.
How CORS works?
CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally, for HTTP request methods that can cause side-effects on data (in particular, for HTTP methods other than GET, or POST with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the HTTP OPTIONS method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.
CORS request/response headers
A CORS request is when a browser makes a request to a server that is not on the same origin as the page that the browser is on. For example, if you have a web page on https://www.example.com
and you make a request to https://api.example.com
, this is a CORS request. The browser will send an Origin
header to the server to tell it where the request is coming from. The server can then decide whether or not to allow the request. If the server allows the request, it will send back a response that includes the Access-Control-Allow-Origin
header. This header tells the browser that the server is allowing the request. The browser will then allow the response to be returned to the web page. If the server does not allow the request, it will not send back the Access-Control-Allow-Origin
header. The browser will then not allow the response to be returned to the web page.
The Access-Control-Allow-Origin
header can have one of three values:
*
- This means that the server allows the request from any origin.null
- This means that the server does not allow the request from any origin.https://www.example.com
- This means that the server only allows the request fromhttps://www.example.com
.
CORS preflight request
A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood. This is done by making a request with the OPTIONS
method to the resource on the other domain, and in the request, the browser includes the Origin
header and the Access-Control-Request-Method
header. The server can then decide whether or not to allow the actual request. If the server allows the actual request, it will send back a response that includes the Access-Control-Allow-Origin
header and the Access-Control-Allow-Methods
header. The browser will then make the actual request. If the server does not allow the actual request, it will not send back the Access-Control-Allow-Origin
header. The browser will not make the actual request.
CORS preflight response headers
The Access-Control-Allow-Methods
header is used in the response to a preflight request to indicate which methods can be used during the actual request. The Access-Control-Allow-Methods
header can have one of two values:
*
- This means that the server allows the actual request to use any method.GET, POST, PUT
- This means that the server allows the actual request to use the GET, POST, and PUT methods.
Enable CORS in AWS API Gateway + Lambda proxy integration
In this section, we will learn how to enable CORS API with AWS CDK. We will use the @aws-cdk/aws-apigateway
module to create an API Gateway REST API and enable CORS.
Create an API Gateway REST API
First, we need to create an API Gateway REST API. We will use the RestApi
class to create an API Gateway REST API. We will pass the restApiName
and description
properties to the RestApi
class constructor. The restApiName
property is the name of the API Gateway REST API. The description
property is the description of the API Gateway REST API.
const api = new apigateway.RestApi(this, 'ApiGateway', {
restApiName: 'ApiGateway',
description: 'ApiGateway',
})
// lambda function
const testFn = new NodejsFunction(this, 'MyFunction', {
entry: './function/index.ts',
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'main',
bundling: {
externalModules: ['aws-sdk'],
minify: true,
},
})
// 👇 add a resource with GET method for demo purposes
api.root.addResource('lambda', {}).addMethod('GET', new LambdaIntegration(testFn))
Enable CORS for API Gateway REST API
I will use the addCorsPreflight
method to enable CORS for the API Gateway REST API. The addCorsPreflight
method takes an object as an argument. The object has the following properties:
// 👇 enable CORS for API Gateway REST API
// 👇 allow CORS for all origins
api.root.addCorsPreflight({
allowOrigins: ['*'],
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization', 'X-Amz-Date', 'X-Api-Key', 'X-Amz-Security-Token', 'X-Amz-User-Agent'],
allowCredentials: true,
})
Enable CORS for Lambda proxy integration
To enable CORS for the Lambda proxy integration, you must add Access-Control-Allow-Origin:domain-name
to the output headers. domain-name
can be *
for any domain name.
export async function main(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
return {
body: JSON.stringify({ message: 'Hello from Lambda!' }),
statusCode: 200,
isBase64Encoded: false,
headers: {
'Content-Type': 'application/json',
// 👇 allow CORS for all origins
'Access-Control-Allow-Origin': '*', // Required for CORS support to work
'Access-Control-Allow-Headers':
'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent',
'Access-Control-Allow-Credentials': 'true', // Required for cookies, authorization headers with HTTPS
'Access-Control-Allow-Methods': 'OPTIONS,GET,PUT,POST,DELETE',
},
}
}
The source code of this article is available on GitHub. You can clone the repository and deploy the API to your AWS account.
Conclusion
In this article, we discussed what CORS is and how it works. We also know how to enable CORS API with AWS CDK. I hope you find this article helpful. If you have any questions, please leave a comment below. Thanks for reading!