skip to Main Content

I am trying to access S3 via aws-sdk in my lambda function.

import S3 from 'aws-sdk/clients/s3';

const s3 = new S3();
const { Contents: results } = await s3.listObjects({ Bucket: process.env.DOCUMENTS_BUCKET_NAME! }).promise()

I have also deployed it successfully using cdk deploy command. But when I test, I get the following error

2022-11-23T15:53:40.891Z    undefined   ERROR   Uncaught Exception  
{
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module 'aws-sdk'nRequire stack:n- /var/task/index.jsn- /var/runtime/index.mjs",
    "stack": [
        "Runtime.ImportModuleError: Error: Cannot find module 'aws-sdk'",
        "Require stack:",
        "- /var/task/index.js",
        "- /var/runtime/index.mjs",
        "    at _loadUserApp (file:///var/runtime/index.mjs:1000:17)",
        "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1035:21)",
        "    at async start (file:///var/runtime/index.mjs:1200:23)",
        "    at async file:///var/runtime/index.mjs:1206:1"
    ]
}

As per the documentation, aws-sdk is always available in the runtime.

Does anyone know what am I doing wrong?

Thank you very much

3

Answers


  1. Chosen as BEST ANSWER

    UPDATED LINK

    Thank you @jarmod, I needed the following dependency

    @aws-sdk/client-s3
    

    My commit with the fix is available here


  2. If your lambda runtime is nodejs18.x my understanding is that SDK v2 is not included in the runtime.

    So, the best solution would be to switch to v3 SDK https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/

    Or, as a workaround in the short term if you use webpack and usually exclude bundling aws-sdk with the following:

    externals: {
        'aws-sdk': 'aws-sdk'
    },
    

    Then simply leave externals out of your webpack.config.js and it will be bundled, but will of course make your lambda larger so not ideal

    Or use nodejs16.x or below in the short term

    Login or Signup to reply.
  3. What I did to fix this issue was to just downgrade my runtime settings from Node.js 18 to Node.js 16.x or below. After that, the test went successful.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search