Summary: How to Add a Node.JS layer to AWS Lambda.
Date: Around 2022
Refactor: 20 February 2025: Checked links and formatting.
In this article I'll show how to add a Node.JS layer to Lambda. By default, Lambda supports Node.JS 12 and 10 native modules and the AWS SDK for JavaScript in Node.JS (subject to change). However, there are many modules for Node.JS available that extend the possibilities. I'll show how to add the Node.JS module paynl to Lambda.
If you're just interested in the layer stuff you can skip this step. I find it useful however to first test a module natively on my workstation before adding it to Lambda:
node --version
from a terminal (like powershell)index.js
with the text console.log("Hello world")
and run it with node index.js
node
which gives you an prompt to run console.log("Hello world")
directlyNow that node runs we can start with the module paynl:
npm install paynl-sdk --save
//jshint esversion:6 console.log("Start testing with paynl node.js module"); var Paynl = require('paynl-sdk'); // In the pay.nl admin, navigate to Manage -> Services and click the SL-code on the left. // From the popup use the apitoken and serviceId, and configure them in the SDK. Paynl.Config.setApiToken('xxxxx'); Paynl.Config.setServiceId('xxxxx'); Paynl.Paymentmethods.getList().forEach( function(paymentmethod) { console.log(paymentmethod.id + ' ' + paymentmethod.visibleName); } ) .catch(error => { console.error(error); });
Start the script (after setting your own token and serviceId) using:
node paynl.js
Which should output something like this:
Start testing with paynl node.js module 10 iDEAL
Now that we know we have a working module and script we can start creating a Layer for Lambda so we can run the script from Lambda.
Follow the following steps to add the paynl module as a layer to Lambda
nodejs
(this must be nodejs)npm init
which will start a wizard to create a package.json filenpm install --save paynl-sdk
Now that we've added a new layer to Lambda we can add it to a Lambda Function.
Follow the following steps to create a Lambda Function using the script above and adding the layer to it:
//jshint esversion:6 var Paynl = require('paynl-sdk'); // In the pay.nl admin, navigate to Manage -> Services and click the SL-code on the left. // From the popup use the apitoken and serviceId, and configure them in the SDK. Paynl.Config.setApiToken('xxxxx); Paynl.Config.setServiceId('xxxxx'); exports.handler = (event, context, callback) => { console.log("Start testing with paynl node.js module"); Paynl.Paymentmethods.getList().forEach( function(paymentmethod) { console.log(paymentmethod.id + ' ' + paymentmethod.visibleName); } ) .catch(error => { console.error(error); }); };
Now we are finished we can check the function:
Now, part of the output should be something like this:
INFO Start testing with paynl node.js module INFO 10 iDEAL