Setting up APIGateway for CORS with the CDK: A Step-by-Step Guide

My API relies on AWS ApiGateway with an underlying AWS Lambda function provisioned through the CDK. The default CORS settings for the API are as follows:

const api = new apiGateway.RestApi(this, "comments-api", {
  defaultCorsPreflightOptions: { allowOrigins: apiGateway.Cors.ALL_ORIGINS }
})

const comments = api.root.addResource("comments")

const comment = comments.addResource("{post_slug}")

comment.addMethod("GET", new apiGateway.LambdaIntegration(listCommentsFunction))

However, it seems that this configuration only covers part of the CORS setup for my API.

  • The response to an OPTIONS request includes the necessary CORS headers but
  • It appears that the response to a
    GET <api>/comments/{post_slug}
    request does not include the required CORS headers

As a result, relying solely on the CDK construct for CORS configuration may not be ideal. Instead, manually configuring an OPTIONS response from my Lambda function might be more effective, like so:

const api = new apiGateway.RestApi(this, "comments-api")

const comments = api.root.addResource("comments")
const comment = comments.addResource("{post_slug}")

comment.addMethod("GET", new apiGateway.LambdaIntegration(listCommentsFunction))
comment.addMethod("OPTIONS", new apiGateway.LambdaIntegration(listCommentsFunction))

This approach ensures that the lambda always responds with the correct headers and avoids conflicting mechanisms for adding CORS headers. It's worth exploring if there is a way to leverage the CDK to configure the response for proper hydration as well.

Answer №1

The code generated by CDK for the OPTIONS method utilizes response overrides - check out this resource for more details: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html

Unfortunately, this feature is not supported in the lambda proxy integration that you are currently using for the GET method. It seems like the only option is to handle CORS headers directly within the lambda source code.

On a side note, I have penned down some insights on setting up CORS for Amazon API Gateway via AWS CDK at this link: .

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform Firestore JSON data into a TypeScript array

Extracting and formatting data from Firebase for visualization purposes can be challenging after successfully working with it in HTML. I am currently dealing with a FirebaseListObservable that contains three value-types, but only one of them needs to be in ...

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...

unable to locate the log generated by a test php elastic beanstalk web application

Recently, I delved into the world of Amazon AWS and decided to experiment with creating a PHP application on Elastic Beanstalk. Opting for the sample application that is automatically generated, I launched my instance successfully and was able to view the ...

When I refresh the page in Angular2, the router parameters do not get loaded again

When loading my application on routers without parameters, everything is normal. However, when trying to use a router with params, the application fails to load. For example: localhost:3000/usersid/:id The code for the router is as follows: const appRou ...

How to implement automatic scrolling to the bottom of a div in React

Currently facing an issue in React: I am looking to implement auto-scroll functionality when the page loads, so it scrolls to the bottom of the messages box. Here is my current code snippet: import Title from "components/seo/Title"; import { u ...

Tips for preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields: isFieldVisible(node: any, field: DocumentField): boolean { if (field.tag === 'ADDR_KOMU') { let field = this.dfs_look(node.children, 'ADDR_A ...

Limit the selected values to calculate a partial sum

Imagine two distinct classes called professor and student: professor.ts export class Professor { id: number name: string } student.ts import { Professor } from "./professor" export class Student { ...

Define security JWT token in the TypeScript REST API using the swagger annotations

Utilizing typescript-rest and incorporating swagger, a package known as typescript-rest-swagger has been integrated. Efforts to include the Bearer token into swagger have proven unsuccessful thus far. Removing the authorization middleware seems to allow ...

Using 'cy.get' to locate elements in Cypress tutorial

Is there a way to search for one element, and if it's not found, search for another element? cy.get(@firstElement).or(@secondElement).click() Can I use a function similar to || in conditions for this scenario? ...

What causes the error message "Expected ':' when utilizing null conditional in TypeScript?"

UPDATE: After receiving CodeCaster's comment, I realized the issue was due to me using TypeScript version 3.5 instead of 3.7+. It was surprising because these checks seemed to be working fine with other Angular elements, such as <div *ngIf="pa ...

Waiting for the execution of the loop to be completed before proceeding - Typescript (Angular)

There's a code snippet triggered on an HTML page when clicked: public salaryConfirmation() { const matDialogConfig: MatDialogConfig = _.cloneDeep(GajiIdSettings.DIALOG_CONFIG); this.warningNameList = []; for(let i=0; i < this.kelolaDat ...

I am unable to get the documentclient put to work, despite trying all possible

My hashkey is a number labeled pid The following code snippet demonstrates the process: app.get('/register', (req, res) => { var params = { TableName:"passengers", Item: { "pid": 55 } }; console.log("Adding a new item..."); docCl ...

Tips for mock nesting a repository in TypeORM?

I'm struggling to figure out how to stub a nested Repository in TypeORM. Can anyone assist me in creating a sinon stub for the code snippet below? I attempted to use some code from another Stack Overflow post in my test file, but it's not working ...

Implementing undefined value acceptance in yup object when using Material-UI

Even though I have clearly specified that the key is optional in my Form, for some reason my input does not accept undefined as a value. Instead, I keep getting this error message: bonusPercentage must be a number type, but the final value was: NaN (cast ...

Defining Multiple Types in Typescript

I have created an interface in a TypeScript definition file named d.ts: declare module myModule { interface IQedModel { field: string | string[]; operator: string; } } In an Angular controller, I have utilized this interface like ...

Typescript - Iterating through CSV columns with precision

I am currently facing a challenge in TypeScript where I need to read a CSV file column by column. Here is an example of the CSV data: Prefix,Suffix Mr,Jr Mrs,Sr After researching on various Stack Overflow questions and reading through TypeScript document ...

Is there a way to combine Vue3, Stripe, and Typescript for seamless integration?

I am currently developing a Vue3 application and running into some issues while trying to integrate Stripe. I am facing difficulty in incorporating it successfully. Here is the code snippet from my Vue3 component named Checkout.vue: <template> .... ...

Can you provide guidance on defining functions using standard syntax and incorporating children in React with TypeScript?

There are multiple ways to type it, such as using the interface React.FC<YourInterface> or explicitly declaring in an interface the type of children as JSX.Element or React.Node. Currently, my approach is: const MyComponent: React.FC<MyInterface& ...

Understanding NestJS Mixins and Their Distinction from Inheritance

After researching, I found that the Nestjs documentation does not include any information about mixins. Here is what I have gathered from my findings on Google and Stack Overflow: A mixin serves as a means of code sharing between classes within Nest. Esse ...

Angular2 routing directs me to a different URL path

In my Angular2 web application, I have set up the following routes: '', '/app', '/login', '/signin', '/validate', '/error', '**': I've defined a route configuration in app.router.t ...