Share code between AWS lambda functions in node.js

See the docs on Using the Callback Parameter at:

  • http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html#nodejs-prog-model-handler-callback

It says this about the result (the callbackPayload in your code):

result – is an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. If an error is provided, this parameter is ignored.

To be JSON.stringify compatible you cannot have any functions there. See the http://json.org/ to see what is valid JSON (only strings, numbers, objects, arrays, true, false and null).

If you want to share code between your AWS Lambda functions in a broad sense, you have to require the same Node module in both of them, so that you can make a common set of functions available to all of your AWS Lamda handlers. But you cannot pass around arbitrary code between them because those will not survive the JSON.stringify.

As a test you can try running this in the browser:

var callbackPayload = {};

callbackPayload.fooData = 'fooFromData';
callbackPayload.fooFunction = function() {return 'fooFromFunction'; };

alert(JSON.stringify(callbackPayload));

(see DEMO) or this in Node:

var callbackPayload = {};

callbackPayload.fooData = 'fooFromData';
callbackPayload.fooFunction = function() {return 'fooFromFunction'; };

console.log(JSON.stringify(callbackPayload));

and see the result:

{"fooData":"fooFromData"}

The functions is stripped out during the serialization process.

Of course you could do something like this:

callbackPayload.fooFunction
    = function() {return 'fooFromFunction'; }.toString();

and get a JSON result:

{"fooData":"fooFromData","fooFunction":"function () {return 'fooFromFunction'; }"}

which you could theoretically eval on the other end but I wouldn't really recommend it.


As of AWS Reinvent 2018, Amazon has introduced Lambda Layers.

Lambda Layers, a way to centrally manage code and data that is shared across multiple functions.

The idea is that now you can put common components in a ZIP file and upload it as a Lambda Layer. Your function code doesn’t need to be changed and can reference the libraries in the layer as it would normally do instead of packaging them separately.