node.jsaws-lambda

How does my NodeJS lambda function find a dependency added to a Lambda layer?


According to the AWS Lambda docs:

  1. Files added to layers are made available to the lambda function inside the /opt directory
  2. the PATH variable already includes the /opt/nodejs directory for nodejs lambda runtimes

In the following lambda function, the index.mjs file is at /var/task/index.mjs, while the dependency (prisma) is at /opt/nodejs/node_modules/@prisma/client

export const handler = async (event) => {
  console.log(`cwd: ${process.cwd()}`); // "cwd: /var/task"
  console.log(`filename: ${import.meta.url}`); // "filename: /var/task/index.mjs"

  const require = createRequire(import.meta.url);
  console.log(require.resolve('@prisma/client')); // "/opt/nodejs/node_modules/@prisma/client/default.js"
};

My question: how is the nodejs dependency resolution algorithm able to resolve a dependency that's present in a totally different part of the directory tree? Is $PATH involved somehow?


Solution

  • The NODE_PATH env var (docs here) controls where the nodejs module resolution algorithm looks when a dependency is not found in the usual way (node_modules folder in project dir and parents)

    Lambda adds /opt/nodejs/node_modules to NODE_PATH, which is why the lambda function is able to resolve dependencies present in a layer.