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" ] }

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달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠