Error: Cannot find module 'nanoid' when invoking lambda function

0

Whenever I'm invoking my lambda function the following error occurs. I have tested various workarounds, but none of them seemed to work.

lambda function:

const AWS = require('aws-sdk');

const { nanoid } = require('nanoid');

const dynamodb = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => { try { // Extract input data from request payload const { input_text, input_file_path } = JSON.parse(event.body);

// Generate a unique ID for the item
const id = nanoid(22);

// Define the DynamoDB item
const params = {
  TableName: 'Filetable',
  Item: {
    id,
    input_text,
    input_file_path,
  },
};


// Save the item to DynamoDB
await dynamodb.put(params).promise();

// Return a successful response
const response = {
  statusCode: 200,
  body: JSON.stringify('Data saved to DynamoDB'),
};

return response;

} catch (error) { // Return an error response if something goes wrong

const response = {

  statusCode: 500,
  body: JSON.stringify('An error occurred'),
};

return response;

} };

Error :

{ "errorType": "Runtime.ImportModuleError", "errorMessage": "Error: Cannot find module 'nanoid'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/index.mjs", "stack": [ "Runtime.ImportModuleError: Error: Cannot find module 'nanoid'", "Require stack:", "- /var/task/index.js", "- /var/runtime/index.mjs", " at _loadUserApp (file:///var/runtime/index.mjs:997:17)", " at async Object.UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1032:21)", " at async start (file:///var/runtime/index.mjs:1195:23)", " at async file:///var/runtime/index.mjs:1201:1" ] }

已提問 10 個月前檢視次數 664 次
2 個答案
0
profile pictureAWS
專家
已回答 10 個月前
  • I have tried the above-given workarounds, although it still gives me the same error.

  • Can you please make sure that you are not following the steps on Mac, as that can cause problem sometime.

  • Yes I have tried them on Windows, yet they still give me the "can not import nanoid" error.

0

I think the issue doesn't lie in creating deployments or layers for nodejs or python for nanoid.

As per https://github.com/ai/nanoid/issues/289 and https://github.com/puyuan/py-nanoid/issues/22, the issue seems to be that using nanoid in AWS Lambda there are chances of running into problems with nanoid not having enough entropy to create secure ids.

One of the workaround provided in those articles is to use Node's crypto that waits for entropy collection or if you intend to use python, it is also good to look into urandom. Check https://lwn.net/Articles/693189/

If the answer is helpful, please click "Accept Answer" and upvote it.

profile picture
已回答 10 個月前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南