Search code examples
amazon-web-servicesaws-lambda

Error when importing `aws-sdk` in AWS Lambda


Working in the Lambda console, using Node v.18 runtime, and am getting really confused while trying to do some really simple beginner tasks. Specifically, I want to write a Lambda that will be called from API Gateway. This called Lambda will contain / call other lambdas.

Any / all advice is welcome.

Here's some code:

index.mjs:

   import AWS from 'aws-sdk';     // <== ERROR HERE
    
    export const handler = async (event) => {
        const lambda = new AWS.Lambda();
    
        try {
            const fetchFunction = // <== ARN for lambda here. We don't even get this far.
        // ... more code to do stuff follows

When I test the Lambda function, it returns an error. Here is the part of the error message that I can't sort out:

  "errorMessage": "Cannot find package 'aws-sdk' imported from /var/task/index.mjs\nDid you mean to import aws-sdk/lib/aws.js?",
  "trace": [
    "Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'aws-sdk' imported from /var/task/index.mjs",
    "Did you mean to import aws-sdk/lib/aws.js?",

I've already researched a solution, but the more information I find, the more overwhelming it becomes.

Can anyone suggest a simple work-around / solution? I'm guessing this is really simple but I'm just not seeing a path to a solution.

Thanks in advance, m


Solution

  • You're importing the v2 SDK. The node 18 lambda runtime only supports the v3 SDK.

    May 2023 Lambda runtimeshttps://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html

    You'll need to update your imports.

    import { LambdaClient, InvokeCommand } from '@aws-sdk/client-lambda';
    

    You can see more of the syntax in the guide. https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/preview/client/lambda/command/InvokeCommand/

    If you're looking for more examples to get you started, I would suggest the Code Library. It has a good collection of examples in V3.