Using AWS SDK in worker

Hi,

I’m implementing the API gateway pattern with a very simple worker here on CloudFlare and I’m trying to invoke an AWS Lambda function directly instead of going through Amazon’s API Gateway which adds a fair bit of latency.

However, I can’t seem to get the worker to call out to AWS due to CloudFlare not implementing XHR, which the AWS SDK uses in a browser environment. There is an internal node/browser switch in the framework, but messing with it will cause the SDK to use node’s standard library OR XHR. Neither one will work on a CF Worker.

I’m sure there are other people trying to talk to AWS in general, and this is a solved issue. I just can’t seem to find the right answer. Could someone point me in the right direction?

Thanks in advance

P.S. The relevant code snippet:

const aws = require(“aws-sdk”);

async function invoke(arn, payload, region = null) {
// Setup SDK
if (!region) region = arn.split(":")[3];
aws.config.region = region;
aws.config.accessKeyId = “INLINE_ACCESS_KEY”;
aws.config.secretAccessKey = “INLINE_SECRET_ACCESS_KEY”;
const lambda = new aws.Lambda();

// Invoke
const params = {
    FunctionName: arn,
    InvocationType: "RequestResponse",
    Payload: JSON.stringify(payload)
};

await lambda.invoke(params).promise();

}

The AWS SDK use node for many calls and also for encryption/decryption of the tokens, it is also enormous which waste a lot of the precious script-size.

But you can use aws4fetch package to make authentication easier and has a Lambda example in the README.

1 Like

Thank you, @thomas4. That did the trick.

1 Like

You can mark the reply as the answer to your question, in case someone else stumbles upon it :slight_smile:

Done :slight_smile:

1 Like