0
votes

I am learning aws lambda, cdk and dynamodb and as a test am trying to update a lambda function code written in aws-sdk js v2 to v3, but after deploying it it doesn't work. I copy pasted the same code in a test lambda function directly in the web console and it worked fine. Here is the error shown in cloudwatch:

{
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module '@aws-sdk/client-dynamodb'\nRequire stack:\n- /var/task/hitcounter.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
    "stack": [
        "Runtime.ImportModuleError: Error: Cannot find module '@aws-sdk/client-dynamodb'",
        "Require stack:",
        "- /var/task/hitcounter.js",
        "- /var/runtime/UserFunction.js",
        "- /var/runtime/index.js",
        "    at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
        "    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
        "    at Object.<anonymous> (/var/runtime/index.js:43:30)",
        "    at Module._compile (internal/modules/cjs/loader.js:1072:14)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)",
        "    at Module.load (internal/modules/cjs/loader.js:937:32)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:778:12)",
        "    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)",
        "    at internal/main/run_main_module.js:17:47"
    ]
}

is there a cdk related settings I have to set or change that allows me to use @aws-sdk v3? I don't want to use v2 since I am starting a project from start and rather use newer API's.

2
what is the code you have for defining the lambda in your stack? The image that the lambda is defined in may not yet have the v3 sdk as part of its default image.lynkfox

2 Answers

1
votes

Lambda environment doesn’t have SDK v3. You must bundle it. Use NodejsLambda construct which will bundle the code for you using esbuild.

1
votes

The AWS Lambda NodeJS environments come with AWS SDK v2.952.0 as of writing this. This is valid for any of the following runtimes: Node.js 10, Node.js 12, Node.js 14.

AWS has an official video on how to make a custom SDK version (including v3) available to your Lambda using Lambda layers.

Alternatively, since you use AWS CDK and the NodejsFunction construct, you can bundle it inside your Lambda artifact directly, by declaring it in the node_modules prop, as described here. Remember that you need to declare aws-sdk v3 as a dependency in your package.json file if you go this way.