Enable CORS for HTTP API in AWS CDK [API Gateway v2]


Borislav Hadzhiev

Last updated: Apr 15, 2022


Photo from Unsplash

Enable CORS for HTTP Api in AWS CDK #

CORS allows us to set up a combination of HTTP headers our backend server responds with to indicate from which domains, other than its own, it receives requests.

By default servers only take requests from applications hosted on the same domain, however HTTP APIs are hosted on the https://amazonaws.com domain and our frontend application might be hosted on https://example.com, which means that we have to configure CORS.

The code for this article is available on GitHub

Let's look at an example of enabling CORS on an HTTP API in CDK:

import {CorsHttpMethod, HttpApi} from '@aws-cdk/aws-apigatewayv2-alpha'; import * as cdk from 'aws-cdk-lib'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); const httpApi = new HttpApi(this, 'cors-demo-api', { description: 'API for CORS demo', corsPreflight: { allowHeaders: [ 'Content-Type', 'X-Amz-Date', 'Authorization', 'X-Api-Key', ], allowMethods: [ CorsHttpMethod.OPTIONS, CorsHttpMethod.GET, CorsHttpMethod.POST, CorsHttpMethod.PUT, CorsHttpMethod.PATCH, CorsHttpMethod.DELETE, ], allowCredentials: true, allowOrigins: ['http://localhost:3000'], // 👇 optionally cache responses to preflight requests // maxAge: cdk.Duration.minutes(5), }, }); } }
If you still use CDK version 1, switch to the cdk-v1 branch in the GitHub repository.

We created an HttpApi, where we've set the corsPreflight prop to enable CORS.

The corsPreflight object consists of the following properties:

allowHeaderswhich HTTP headers the frontend is allowed to use, when making requests to our HTTP API
allowMethodswhich HTTP methods the frontend is allowed to use, when making requests to our HTTP API
allowCredentialswhether credentials (cookies, auth headers) are included in the CORS requests to the HTTP API
allowOriginswhich origins are allowed to make requests to our HTTP API. If your domain is https://example.com and it needs to make requests ot the API, add it to allowOrigins.
maxAgethe duration, for which the browser will cache the response from a preflight requests. Set this if you're worried about performance. By default responses don't get cached.

Let's run the deploy command:

npx aws-cdk deploy

If we look at the API named cors-demo-api, we can see that we've successfully set up CORS:

http api cors

Clean up #

To delete the resources we've provisioned, issue the destroy command:

npx aws-cdk destroy

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.