AWS Layer: Generate nodejs Zip Layer File Based on the Lambda's Dependencies

We want to create an AWS layer zip file containing all the node_modules used by a particular AWS lambda function.

Stepwise, here’s how we can do it:

Add a script in the lambda function’s package.json. Let’s call it build:layer. It should do the following:

  1. Create nodejs directory (mkdir nodejs)
  2. Copy Lambda’s package.json to nodejs (cp package.json ./nodejs)
  3. Change directory to nodejs (cd nodejs)
  4. Installing node_modules while omitting dev dependencies (npm i --omit=dev)
  5. Move out of nodejs (cd ..)
  6. Zip the contents of nodejs in nodejs.zip (zip -r nodejs.zip nodejs)
  7. Remove the temporary folder nodejs and its contents ( rm -rf nodejs)

Here’s the full script:

"build:layer": "mkdir nodejs && cp package.json ./nodejs && cd nodejs && npm i --omit=dev && cd .. && zip -r nodejs.zip nodejs && rm -rf nodejs"

Now, you can upload this generated nodejs.zip file as an AWS layer and use it in your lambda code.




nodejs  aws 

See also

When you purchase through links on techighness.com, I may earn an affiliate commission.