The imported constant is throwing an 'Invalid lambda response received' error when specifying headers

Currently, I am utilizing the CDK TypeScript Lambda stack which is connected to an API Gateway. Everything seems to be functioning perfectly when I use the following response:

const res = await request<ResponseModel>(req);
return {
    statusCode: res.status,
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': true
    },
    body: JSON.stringify(res.data)
};

However, my attempt to set the headers using a common constant resulted in failure:

// common-headers.ts
export const CommonResponseHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Credentials': true
};

//function.ts
import { CommonResponseHeaders } from '../../common/common-headers';

const res = await request<ResponseModel>(req);
return {
    statusCode: res.status,
    headers: CommonResponseHeaders,
    body: JSON.stringify(res.data)
};

//stack.ts
const function = {
    name: 'myFunction',
    runtime: Runtime.NODEJS_14_X,
    entry: path.join(__dirname, './function.ts'),
    vpcSubnets: {
      subnetType: SubnetType.PRIVATE_WITH_EGRESS
    },
    handler: 'handler',
    environment: {
      ...SomeDefaultVariables
    }
  }
const lambda = new NodejsFunction(this, function.name, function);
const functionUrl = lambda.addFunctionUrl({
authType: FunctionUrlAuthType.NONE,
cors: {
  allowedOrigins: ['*'],
}
});
new CfnOutput(this, `${function.name}-FunctionUrl`, {
value: functionUrl.url,
});

An invalid lambda response was received with Invalid API Gateway Response Keys: {'trace', 'errorType', 'errorMessage'} in {'errorType': 'TypeError', 'errorMessage': "Cannot read property 'trim' of undefined", 'trace': ["TypeError: Cannot read property 'trim' of undefined", ' at Object. (/var/task/index.js:10924:40)', ' at Module._compile (internal/modules/cjs/loader.js:1085:14)', ' at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)', ' at Module.load (internal/modules/cjs/loader.js:950:32)', ' at Function.Module._load (internal/modules/cjs/loader.js:790:12)', '
at Module.require (internal/modules/cjs/loader.js:974:19)', ' at require (internal/modules/cjs/helpers.js:101:18)', ' at _tryRequireFile (/var/runtime/UserFunction.js:72:32)', ' at _tryRequire (/var/runtime/UserFunction.js:160:20)', ' at _loadUserApp (/var/runtime/UserFunction.js:219:12)']}

Any assistance would be greatly appreciated!

Answer №1

Your code is returning headers that do not match what API Gateway expects. According to AWS documentation, the Lambda function should return output in a specific format if the response succeeds:

{
    statusCode: "...",            // HTTP status code
    headers: { 
        custom-header: "..."      // custom header
    },
    body: "...",                  // JSON string
    isBase64Encoded:  true|false  // binary support flag
}

The error you are experiencing is likely caused by something else in your project and it is not being handled properly. If you encounter an error, make sure to return a 4xx or 5xx status code in the specified format. It could be related to the CDK framework your code is using. Here are some possible reasons for the issue:

  1. There is a known issue with AWS amplify where misspelling approot as appRoot resulted in a similar error related to the trim function. Check out this issue for more information.

  2. Ensure your TypeScript transpilation settings match the Node.js runtime you intend to use. Refer to AWS documentation for guidance on runtimes.

  3. When utilizing NodeJS 14.x, verify that your imports align with the requirements of that version to avoid mistakes from code copied elsewhere. Review this helpful post for proper handling of local file imports.

     // File path corresponds to ../../common/common-headers.ts
     import { CommonResponseHeaders } from '../../common/common-headers.js';
    

Answer №2

The problem lies in its inability to properly recognize the imports.

Have you ensured that you have imported common-headers.ts file correctly to access CommonResponseHeaders?

You may want to define paths in a separate file named config.json, where you can do something like this:

Just remember to include the path to the common-headers.ts file under include.

{
    "compilerOptions": {
        ...
    },
    "include": [
        "./src/**/*",
        "./common/**/*"
    ]
}

Try deploying with CDK, which should help include your common-headers.ts file correctly and resolve the issue.

Note: Still not resolved? Double-check your import statement to ensure you are importing CommonResponseHeaders from common-headers.ts file accurately.

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

Unable to dispatch asynchronous post request

I am currently attempting to wait for a post request. I have discovered the request-promise-native package, which allows for awaiting requests. While this method is effective for GET requests, it seems to be ineffective with POST. The URL and auth hash hav ...

Declaration of function with extra attributes

Is there a way to define a type for a function that includes additional properties like this? foo({ name: 'john' }) foo.type I tried the following solution, but TypeScript seems to think that foo only returns the function and cannot be called wi ...

Is there a tool that can automatically arrange and resolve TypeScript dependencies, with or without the use of _references.ts file?

Currently, I am working on understanding the new workflow for "_references.ts" and I feel like there is something missing when it comes to using multiple files without external modules in order to produce correctly ordered ".js" code. To start with, I took ...

Make sure to pass refs when using FC children with Next.js Links

I am struggling to understand the documentation in next.js regarding passing refs to children functional components. It's confusing to me and I'm finding it difficult to implement. For example, let's consider a functional component that dis ...

Combining class and data within an iteration while utilizing ngFor

I have a dynamic table with rows generated using ngFor <tbody> <tr *ngFor="let item of Details"> <div class="row details-row row-cols-lg-2 row-cols-1" *ngIf="closureDetails"> <div ...

Oops! Angular2 couldn't find a provider for HttpHandler

I have been working on implementing HttpCache through an interceptor. Below is the code snippet for caching-interceptor.service.ts: import { HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http' import ...

Can an Ionic app perform a background task at a scheduled time?

Q: is there a way to perform a task that repeats every x minutes in the background? ...

Warning: The attribute 'EyeDropper' is not recognized within the context of 'Window & typeof globalThis'

Attempting to utilize "window.EyeDropper" in a project that combines vue2 and TypeScript. When writing the following code: console.log(window.EyeDropper); An error message is generated by my Vetur plugin: Property 'EyeDropper' does not exist on ...

Encountering issues when utilizing the 'got' package

I encountered an issue while using 'got' version '11.8.3', resulting in the following error: /app/node_modules/got/dist/source/core/index.js:696 throw new TypeError('The payload has been already provided'); ^ TypeError: The p ...

Utilize function.apply in Typescript to pass generic parameters

For a personal project I've been working on (originally started in Javascript), I needed to make http requests. To streamline this process, I opted to use Axios and created a file called http.js with the code below: import axios from 'axios' ...

The namespace does not contain any exported member

Every time I attempt to code this in TypeScript, an error pops up stating The namespace Bar does not have a member named Qux exported. What could possibly be causing this and how can I resolve it? class Foo {} namespace Bar { export const Qux = Foo ...

Azure function indicates a successful status despite receiving a result code of 500

I have an Azure function containing some logic with a basic try-catch structure (code shortened). try { // perform logic here that may fail } catch (ex) { context.log(`Logging exception details: ${ex.message}`); context.res ...

Using Typescript to create a union of functions

There are two different types of functions: one that returns a string and the other that returns a Promise<string>. Now, I am looking to create a function that can wrap both types, but I need to be able to distinguish between them when invoking the f ...

Typescript fails to properly identify the yield keyword within a generator function or generator body

Here is the code for my generator function: function* generatorFunction(input: number[]): IterableIterator<number> { input.forEach((num) => { yield num; }); An error occurred during linting: A 'yield' expression is only allowed ...

Tips on retrieving data from a JSON object

I'm currently on a project involving Angular 5, and I'm still new to using Angular so I'm facing some challenges retrieving values from a JSON object. Here's the JSON response: [{"student_guid":"198","seconds":510,"session_count":0,"un ...

Utilizing Node modules in TypeScript, Angular 2, and SystemJS: A Comprehensive Guide

In the process of developing a simple Angular 2 application, I am constructing a class named User. This class includes a function called validPassword() which utilizes the bcrypt library to validate user passwords: import { compareSync, genSaltSync, hashS ...

angular determine if a column exists within a matCellDef iteration

Is there a way to check a column in an ng for loop in Angular without using the logic "{{element[p.key] != null ? '$' : ''}}" for a specific column or excluding a specific column? View image description here #html code <table mat-t ...

Encountering an issue with Angular virtual scrolling: ViewDestroyedError arises when trying to utilize a destroyed view during detectChanges operation

My implementation involves using virtual scrolling from the cdk within a trigger-opening sidenav on a mat-radio element. Here is the code snippet: ts - ... @Component({ selector: 'app-generic-options-list', templateUrl: './generic-opt ...

Comprehending the concepts of Observables, Promises, using "this" keyword, and transferring data within Angular with TypeScript

I am trying to figure out why I keep receiving the error message: "Uncaught (in promise): TypeError: this.dealership is undefined" when working with the authentication.service.ts file. export class AuthenticationService { private currentUserSubject: ...

Is there a way to sort a MUI Datatable based on the value rather than the custom body render content?

Previously, the temperature (of type Number) was displayed as a string with "° C" appended to it before implementing custom filter options. Despite this formatting change, the value was sort-able (ascending and descending). However, after adding the custo ...