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

avatar

Borislav Hadzhiev

Wed May 12 20212 min read

In order to enable CORS for an HTTP API we have to pass and configure the `corsPreflight` prop when instantiating the HttpApi class.

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:

lib/cdk-starter-stack.ts
import {CorsHttpMethod, HttpApi} from '@aws-cdk/aws-apigatewayv2';
import * as cdk from '@aws-cdk/core';

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),
      },
    });
  }
}

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

The corsPreflight object consists of the following properties:

NameDescription
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 execute a deployment:

shell
npx 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, execute the destroy command:

shell
npx cdk destroy

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee