Top 10 Solutions for API Gateway CORS Implementation

Jennie Lee
8 min readMar 25, 2024

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

Introduction to API Gateway in AWS ecosystem

API Gateway is a powerful and fully managed service in the AWS ecosystem that makes it easy to create, deploy, and manage APIs at any scale. It allows developers to build, secure, and monitor APIs for applications running in the cloud or on-premises.

With API Gateway, developers can take advantage of features such as request validation, throttling, and authorization. It acts as a front-door for APIs and provides a seamless integration with other AWS services. This makes it an ideal choice for building serverless architectures and microservices-based applications.

API Gateway has several common use cases. One of the most popular use cases is the invocation of Lambda functions. Developers can create an API endpoint in API Gateway and configure it to directly invoke a Lambda function, providing a serverless and scalable solution for building RESTful APIs. API Gateway also integrates seamlessly with other AWS services, allowing developers to connect their APIs to services such as AWS DynamoDB, AWS S3, or AWS Step Functions.

Additionally, API Gateway provides HTTP integrations, which allow developers to connect their APIs to existing HTTP endpoints. This enables them to easily migrate existing APIs to API Gateway and take advantage of its features and benefits without making significant changes to their underlying infrastructure.

Understanding CORS as a security mechanism

Cross-Origin Resource Sharing (CORS) is a security mechanism implemented by web browsers to control access to resources that are hosted on a different domain. It is an essential security measure for web applications that make requests to APIs hosted on different origins.

Without CORS, web browsers enforce the same-origin policy, which prevents web pages from making requests to APIs on different domains. However, this policy can be too restrictive for modern web applications, which often need to consume data or services from multiple origins.

CORS allows web applications to specify which domains are allowed to access their resources by adding specific headers to HTTP responses. These headers include Access-Control-Allow-Origin, which specifies the allowed origins, and Access-Control-Allow-Methods, which defines the HTTP methods allowed for cross-origin requests.

All major web browsers support CORS and enforce its rules to protect users from malicious cross-origin requests. As a result, APIs that do not implement CORS correctly will be inaccessible to web applications running in these browsers.

API Gateway provides built-in support for CORS headers, allowing developers to easily enable CORS for their APIs. By configuring the appropriate CORS settings in API Gateway, developers can ensure that their APIs can be accessed by web applications running on different origins.

Difference between REST API and HTTP API in API Gateway

API Gateway provides two different API types: REST API and HTTP API. Understanding the differences between these two API types is crucial when deciding which one to use for a particular use case.

REST API is the traditional API type in API Gateway and offers a rich set of features and configuration options. It supports various API development styles, including defining resources, methods, and integration configurations using the API Gateway graphical interface or by importing API definitions in formats such as Swagger or OpenAPI.

On the other hand, HTTP API is a newer and lower-cost alternative to REST API. It provides a simpler and more efficient format for defining APIs, making it easier to create and manage APIs at scale. With HTTP API, developers can define routes and the corresponding integrations using a simplified syntax.

Another important difference between REST API and HTTP API is the payload version. REST API uses version 1.0 of the payload format, while HTTP API uses version 2.0. This can affect the compatibility of the APIs, as they might expect different request and response formats.

To choose the appropriate API type, developers should consider the specific requirements and constraints of their use case. REST API provides more flexibility and features, making it suitable for complex APIs with advanced configuration needs. On the other hand, HTTP API offers a more streamlined experience and cost benefits, making it a preferred choice for simpler APIs or projects with budget considerations.

Enabling CORS in API Gateway

Enabling CORS in API Gateway involves configuring the appropriate CORS headers on API endpoints. API Gateway provides multiple ways to enable CORS based on the integration pattern used.

A. Proxy Integration with REST API

Proxy integration allows developers to configure an API endpoint to proxy a request to another endpoint, such as a Lambda function or an HTTP endpoint. To enable CORS for a proxy integration with REST API, the following steps can be followed:

  1. In the API Gateway console, select the desired API and navigate to the desired resource and method.
  2. Under the “Integration Request” section, expand the “HTTP Headers” settings.
  3. Add the following headers:
  • Access-Control-Allow-Origin: The value of this header specifies the allowed origins. Use “*” to allow requests from any origin, or specify specific origins separated by commas.
  • Access-Control-Allow-Headers: The value of this header specifies the allowed headers in the preflight request.
  • Access-Control-Allow-Methods: The value of this header specifies the allowed HTTP methods for cross-origin requests.
  1. Save the changes and deploy the API to make the CORS settings effective.

Here’s a sample code written in TypeScript using AWS CDK to enable CORS for a proxy integration with REST API:

import { aws_apigateway as apigateway } from 'aws-cdk-lib';

const api = new apigateway.RestApi(stack, 'MyApi');
const resource = api.root.addResource('my-resource');
const method = resource.addMethod('GET', new apigateway.HttpIntegration('https://example.com'));

method.addRequestValidator('Validator', { validateRequestParameters: true });

method.methodArn; // ARN of the API Gateway method

In this example, we enable CORS for a GET method of an API resource. The Access-Control-Allow-Origin, Access-Control-Allow-Headers, and Access-Control-Allow-Methods headers are added to the integration request to allow cross-origin requests.

The AWS CDK code sample demonstrates how to use the HttpIntegration class to create an HTTP-based integration. It also shows how to add a request validator to validate the request parameters.

B. Proxy Integration with HTTP API

HTTP API provides a simpler and more efficient way to define APIs. Enabling CORS for a proxy integration with HTTP API involves similar steps as for a proxy integration with REST API:

  1. In the API Gateway console, select the desired API and navigate to the desired route and integration.
  2. Under the “CORS” section, specify the allowed origins, headers, and methods.
  3. Save the changes and deploy the API to make the CORS settings effective.

Here’s a sample code written in TypeScript using AWS CDK to enable CORS for a proxy integration with HTTP API:

import { aws_apigatewayv2 as apigatewayv2 } from 'aws-cdk-lib';

const api = new apigatewayv2.HttpApi(stack, 'MyApi');
const integration = new apigatewayv2.HttpProxyIntegration({
url: 'https://example.com',
});

const route = api.addRoutes({
path: '/my-resource',
methods: [apigatewayv2.HttpMethod.GET],
integration: integration,
});

route.addCorsPreflight({
allowOrigins: ['*'],
allowMethods: [apigatewayv2.HttpMethod.GET],
allowHeaders: [apigatewayv2.HttpHeader.CONTENT_TYPE],
});

In this example, we create an HTTP API and add a route with a proxy integration using the HttpProxyIntegration class. We then configure CORS settings using the addCorsPreflight method to allow cross-origin requests for the specified origins, methods, and headers.

C. Custom Integration with REST API

Custom integration allows developers to define the integration logic using an AWS service or an HTTP endpoint. To enable CORS for a custom integration with REST API, the following steps can be followed:

  1. In the API Gateway console, select the desired API and navigate to the desired resource and method.
  2. Under the “Method Response” section, expand the desired response status code and add the following headers:
  • Access-Control-Allow-Origin: The value of this header specifies the allowed origins. Use “*” to allow requests from any origin, or specify specific origins separated by commas.
  • Access-Control-Allow-Headers: The value of this header specifies the allowed headers in the preflight request.
  • Access-Control-Allow-Methods: The value of this header specifies the allowed HTTP methods for cross-origin requests.
  1. Under the “Integration Response” section, expand the desired response status code and map the appropriate response headers.
  2. Save the changes and deploy the API to make the CORS settings effective.

Here’s a sample code written in TypeScript using AWS CDK to enable CORS for a custom integration with REST API:

import { aws_lambda as lambda, aws_apigateway as apigateway, aws_apigatewayv2 as apigatewayv2, aws_iam as iam } from 'aws-cdk-lib';

const lambdaFunction = new lambda.Function(stack, 'MyLambda', {
// ...
});

const api = new apigateway.RestApi(stack, 'MyApi');
const resource = api.root.addResource('my-resource');
const method = resource.addMethod('GET', new apigateway.AwsIntegration({
service: 'lambda',
integrationHttpMethod: 'POST',
path: lambdaFunction.functionArn,
options: {
credentialsRole: new iam.Role(stack, 'CredentialsRole', {
// ...
}),
requestTemplates: {
'application/json': '{ "statusCode": 200 }',
},
integrationResponses: [{
statusCode: '200',
responseTemplates: {
'application/json': '{ "message": "Hello, World!" }',
},
}],
},
}));

method.methodArn; // ARN of the API Gateway method

In this example, we enable CORS for a GET method of a custom integration with REST API. We add the necessary headers in the method response and integration response to allow cross-origin requests. The AWS CDK code sample demonstrates how to use the AwsIntegration class to create an integration with a Lambda function.

Considerations for API Gateway CORS Implementation When implementing CORS in API Gateway, there are several considerations to keep in mind:

  1. Request Validation: Ensure that request validation is enabled for API Gateway, as this helps protect against unexpected or malicious payloads.
  2. Credentials: Consider using credentials to restrict access to specific APIs based on authentication and authorization requirements.
  3. Preflight Requests: Browser security enforces the use of preflight requests for cross-origin requests that are not simple requests (e.g., POST requests with certain content types). Pay attention to OPTIONS requests in API Gateway to handle CORS preflight requests properly.
  4. Caching: Be aware of caching implications when enabling CORS in API Gateway. CORS headers can vary by origin, so caching based on the request’s headers may not be appropriate.
  5. Wildcard Origins: Be cautious when using wildcard (*) as the allowed origin for CORS. While it is convenient for development and simple use cases, it is not recommended for production environments due to potential security risks.
  6. Security Considerations: Ensure that any sensitive information or operations exposed through APIs are adequately protected using appropriate authentication and authorization mechanisms.

In conclusion, enabling CORS in API Gateway is essential for web applications that need to consume APIs hosted on different origins. API Gateway makes it easy to configure CORS headers for different integration patterns, allowing developers to ensure their APIs are accessible to web applications running on multiple domains. By following the step-by-step instructions provided in this article and considering the relevant considerations, developers can enable CORS in API Gateway and build secure and scalable APIs for their applications. In future articles, we will explore topics such as authorization and request/response validation in API Gateway. Leave a comment if there are specific topics you would like us to cover in-depth.

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

--

--