- create a folder in your local machine called nodejs
- put your "shared" logic in that folder like /nodejs/shared.js
- you can zip this nodejs folder and upload as a layer
- in your lambda code require the shared.js as
const shared = require('/opt/nodejs/shared.js')
Links:
- Lambda layers: https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html
- Detailed guide: https://explainexample.com/computers/aws/aws-lambda-layers-node-app
- Using layers with SAM: https://docs.aws.amazon.com/serverlessrepo/latest/devguide/sharing-lambda-layers.html
node.js - How to share my own custom fucntions on AWS lambda nodejs - Stack Overflow
node.js - Use custom Layers in NodeJS lambda - Stack Overflow
How to upload a Lambda function with Node.js SDKs and dependencies?
How to use Sharp in AWS Lambda function? I keep getting errors. (node.js, for image resizing)
Videos
At first, about the layer folder structure, all your shared files have to store under nodejs folder. This means, your layer will look like this:
05-24 07:09PM ~/poc/webapp-layers $ ls index.js layers node_modules package-lock.json package.json serverless.yml
~/poc/webapp-layers $ tree
...
layers/
nodejs/
accounts/
index.js
...
But, with the above structure, you have to update your lambda function to require accounts modules
const accounts = require("/opt/nodejs/accounts");
If you want to use
const { accounts } = require("layers");
the structure should be:
~/poc/webapp-layers $ tree
...
layers/
nodejs/
node_modules/ <---------------
layer/
index.js
accounts/
index.js
And layer/index.js just re-export accounts module
"use strict";
const accounts = require("../accounts");
exports.accounts = accounts;
The error message shows it cannot find layers module.
In your code, there is const {accounts} = require("layers");
It means it is importing from node_modules, but in your package.json, there is no layers package. So you should change it to require("./layers") for custom-created module.
I think it will be helpful for your issue.