Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import or require not working on aws lamda

I am writing a lambda function on aws. I want to send user data after they signup to my mongodb database. I triggered the lambda function using "pre authenticate" method. however, "I am getting this error " preauthentication failed with error cannot find package 'aws-sdk' imported from /var/task/index.mjs. "

my lambda function code:

import AWS  from 'aws-sdk'
import {MongoClient} from 'mongodb'

exports.handler = async (event) => {
 try{
     // Retrieve the user data from the event object
  const userData = event.request.userAttributes;

  // Connect to the MongoDB database
  const client = await MongoClient.connect("database url", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  const db = client.db("Cluster0");
  const collection = db.collection("users");

  // Insert the user data into the collection
  await collection.insertOne(userData);

  // Close the database connection
  client.close();
 }catch(error){
    callback(error, event)
 }
};

my question is do I have to install mongodb and aws sdk on lambda function folder? I am writing lambda function from aws website.

like image 418
Sajib Hossain Avatar asked Oct 28 '25 02:10

Sajib Hossain


1 Answers

cannot find package 'aws-sdk' imported from /var/task/index.mjs

This error is usually caused by using the SDK V2 import statements while using a Lambda runtime which uses SDK V3.

I am guessing you are using the new node runtime 18 on Lambda. This runtime uses the Node SDK V3 which supports modular imports like so:

const { S3Client } = require("@aws-sdk/client-s3");

You can either change to a lower runtime or change your code to suit the Node V3 SDK imports:

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/#modularized-packages

I also don't believe Lambda runtimes have the MongoDB client built in, which means you will need to create the package locally or use a Lambda Layer

https://www.mongodb.com/developer/products/atlas/serverless-development-lambda-atlas/

If you are not tied down to MongoDB, you can use DynamoDB which has a built in client for the Lambda runtime.

like image 175
Lee Hannigan Avatar answered Oct 29 '25 17:10

Lee Hannigan