user1683766 user1683766 - 5 months ago 25
Node.js Question

Accessing Lambda context object in other files

I have a NodeJS AWS Lambda function which contains of multiple files. In the index.js I do the regular

exports.handler = function (event,context) {…}

I also have a config.js file which handles various settings and module.exports a config object. This config file is required in several other files that all need access to these settings (default values, db settings, etc.). I don't necessarily need to use it in index.js itself.

However, I need to set some settings inside the config module according to the alias of the Lambda function (for example which DynamoDB table suffix to use). While it's no problem to get the alias name via
(in my case PROD or STAGE) inside exports.handler, I don't have access to it in my config file (which is required all over the place).

What would be the best way to make the context object available in my config module and how would I do it without running into circular dependencies (because it is needed before exports.handler is finished)?

Inside exports.handler a lot of async code from multiple files which all require the config is executed. They all need to know which alias is running.

The question is less about how to use aliases but more how to make the context object available in other files.



Just set the variables at the top of your handler before you invoke the async functions:

const config = require('./config')
const someAsyncFunction = require('./someAsyncFunction')
exports.handler = function (event, context) {
  config.invokedFunctionArn = context.invokedFunctionArn