AWS Lambda Layers :: How to add and require a simple js file from a lambda layer

In my serverless project, I have some js files that are being repeated among several lambdas functions, and I want to add theses files inside my lambda layer and use them as a simple require() inside each lambda function.

I am already using a lambda layer to share npm packages among lambdas, and it is working as expected, with the structure: nodejs/node_modules/{package-name}/

But I dont want to transform my simple files into a private npm package to make it work.

I’ve tried to create a new folder inside nodejs folder, called /custom_libs

So my attempt is nodejs/custom_libs/lib-name.js and the require inside lambda function is:

require("/opt/custom_libs/lib-name.js");

But it is not working.

Any thoughts on how can I achieve this ?

Thanks

2 Likes

Hi Daniel,

I met the same issue as yours. Have you found the solution yet? thanks.

Best.

Hi Kanes!

Yes, I found a solution, but not using lambda layers.

I kept my custom libs in a folder inside my project and referred to them using relative paths (eg: require(’…/…/…/custom_libs/myLib’).

Later I got another approach, setting a constant with the absolute path for Node that is ‘/var/task’ and appended them in the require path.

Note that you need to use serverless package commands, include and exclude , to insert this folder inside each lambda. Or use webpack as well to do this kind of job.

Cya!

1 Like

Hi Daniel!

Thanks for your helpful response! I am actually using the first solution of your response. One thing makes me want to switch to Lambda Layer is that the deployment take toooooo long! I will try the second approach later for comparison. Anyway, thank you very much!!!

Best.

1 Like

Yes, I suppose that the command package, include/exclude, that takes longer to process. Maybe if you use webpack to bundle include/exclude files, this process will be reduced.

Regards,
Daniel