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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With