Lambda Layer "Cannot Find Module": The Node.js Folder Fix

Logeshwaran
—

A Lambda layer Cannot find module error usually means Node.js cannot resolve a dependency from the ZIP layout or the layer version attached to your function. Put the dependency at nodejs/node_modules/<package> inside the ZIP, so Lambda extracts it to /opt/nodejs/node_modules/<package>. The easy-to-miss detail is that successfully publishing a layer does not prove Node.js can import anything from it: AWS accepts archives with the wrong root folder, and a function may still point to an older immutable version. Inspect both before reinstalling packages.

⚡ Quick Answer

• Build: mkdir -p nodejs && npm install --prefix nodejs lodash, then zip -r layer.zip nodejs/.

• Verify: unzip -l layer.zip; files should begin with nodejs/node_modules/, without an extra parent directory.

• Console: Lambda → Functions → your function → Layers. Inspect its exact layer version ARN.

• CLI: aws lambda get-function-configuration --function-name my-function --query 'Layers[].Arn'.

Follow the complete working example or inspect the deployed ZIP before changing production.

Jake has a phone shop and a tiny Lambda function that prepares repair notifications. He extracted a shared helper into a layer so the same dependency would not be bundled into several functions. His change appeared successful in the console, but his next test returned Runtime.ImportModuleError instead of an order confirmation.

The failure interrupted a $249.99 screen repair booking, though the layer itself did not create that charge. Jake wants a reliable fix without guessing at npm versions or changing permissions all afternoon. The useful question is whether his package is missing, hidden under the wrong folder, incompatible with the runtime, or attached through an old version.

You can answer those questions in that order. The folder names inside your ZIP and the version ARN attached to the function provide stronger evidence than what your local project tree looks like. Every packaging change should finish with a fresh import test in the actual Lambda environment.

Jake: "But the console says my layer uploaded successfully. Does that not mean the module is there?"

Ethan: "Uploading proves Lambda received a ZIP. It does not prove its internal folders match the module search path. Open the archive before touching the function code."

Read the error before changing your layer

When your function fails during initialization, CloudWatch often reports Runtime.ImportModuleError followed by Error: Cannot find module 'lodash' or another package name. The module name matters more than the surrounding stack trace at first: it tells you what Node.js attempted to import. Compare that name exactly with the directory under node_modules, including the package scope when present.

The Require stack in a CommonJS error can tell you which file made the failing require() call. If that file is /var/task/index.js, the handler is trying to load something at startup. If it is inside a dependency, a package in your layer may exist but have a missing transitive dependency or an incompatible export.

An import failure happens before normal handler business logic when the problematic import is at module scope. That is why you may see an INIT failure with no application log message from your handler. A module loaded dynamically inside the handler can fail during an invocation instead, so the precise failure stage is helpful but not the only diagnostic.

Your first action should be to save the entire error message, the function runtime and architecture, and the layer ARNs. Then inspect the ZIP and deployed filesystem. Repeatedly publishing the same badly structured archive only creates new immutable versions of the same problem.

Understand where Lambda actually mounts layer files

If the ZIP contains nodejs/node_modules/lodash/package.json, Lambda extracts that file as /opt/nodejs/node_modules/lodash/package.json. The /opt directory is the shared location for attached layer content. Your function deployment package is separate, under /var/task, so keeping those two roots straight eliminates many misleading paths.

Node.js managed runtimes include layer dependency directories in their module search configuration. A general folder nodejs/node_modules works for supported Node.js layer layouts. Version-specific paths such as nodejs/node22/node_modules are also documented; match the directory to the runtime actually deployed rather than inventing a folder name.

An installed dependency normally contains its own package.json and JavaScript files, and npm may add nested dependencies beneath it. Those files are part of the installed package and should remain in the archive. The parent nodejs/package.json and lockfile help reproducible builds, but Lambda finds the installed module by its installed location.

If your ZIP starts with node_modules instead of nodejs, extraction puts it under /opt/node_modules, which is not the standard Node.js layer lookup path. If the ZIP starts with my-project/nodejs, extraction adds an extra directory before the required path. Neither mistake is fixed by attaching the layer again.

layer.zip
└── nodejs/
    └── node_modules/
        └── lodash/
            ├── package.json
            └── lodash.js

Runtime: /opt/nodejs/node_modules/lodash/

Spot the ZIP root error in seconds

You may see the correct folders on your laptop and still create the wrong archive. ZIP tools store paths relative to the selection and working directory at packaging time. The safest habit is to list archive contents immediately after creation, then inspect the first path component in each entry.

The archive filename does not matter to Node.js, but the internal path does. You can call it shared-dependencies.zip or layer.zip; either works if the ZIP root contains nodejs. What matters is that nodejs is not buried beneath a second project folder or replaced by node_modules.

On Linux or macOS, zip -r layer.zip nodejs/ from the directory containing nodejs preserves the correct parent folder. On PowerShell, Compress-Archive -Path .\nodejs -DestinationPath .\layer.zip includes the folder itself. If you instead archive only the contents of nodejs, the ZIP can start one level too deep.

If inspection shows an extra root, rebuild from a clean staging directory rather than trying to modify the ZIP in place. That is faster to reason about, easier to review, and less likely to leave duplicate entries or unexpected files. Only publish once the archive listing matches your intended tree.

ZIP path starts withResult
nodejs/node_modules/lodash/...Correct: resolves under /opt/nodejs/node_modules
node_modules/lodash/...Wrong: missing nodejs directory
project/nodejs/node_modules/lodash/...Wrong: extra top-level project directory
nodejs/node_modules/@scope/pkg/...Correct: scoped npm dependency
unzip -l layer.zip | head -40
# PowerShell:
Add-Type -AssemblyName System.IO.Compression.FileSystem
[IO.Compression.ZipFile]::OpenRead((Resolve-Path .\layer.zip)).Entries.FullName | Select-Object -First 40

Build a layer from an empty folder to a working import

You can demonstrate the entire fix without native dependencies by using lodash, a common JavaScript package. Start in an empty directory and install it beneath nodejs. This exercise proves the folder structure, while leaving OS-specific binary compilation out of the first test.

The example uses a Node.js runtime supported by your function, with Node.js 22 as the concrete runtime identifier in the publication example. Install a matching local Node.js/npm toolchain to minimize avoidable package differences. The package itself is ordinary JavaScript, so the example is deliberately simpler than a sharp or bcrypt deployment.

Create the archive from the directory above nodejs. Inspect the resulting ZIP for entries beneath nodejs/node_modules/lodash and publish a layer version. Finally, attach that exact version ARN to the function and invoke it with a basic test event.

The result is a transparent chain of evidence: npm installed the module in the required directory, the ZIP preserved the directory, the published version pointed to that ZIP, and the function attached that version. If any link fails, you know which part to revisit rather than rebuilding everything.

  1. Create an empty working directory and enter it.
  2. Install lodash into the required nodejs prefix.
  3. Create a ZIP containing nodejs at the archive root.
  4. Publish a numbered layer version for a supported runtime.
  5. Attach the returned ARN alongside any layers you intend to retain.
  6. Invoke a minimal function and inspect its result.
mkdir lambda-layer-demo
cd lambda-layer-demo
mkdir nodejs
npm install --prefix nodejs lodash
zip -r layer.zip nodejs/
unzip -l layer.zip | grep "nodejs/node_modules/lodash" | head
aws lambda publish-layer-version \
  --layer-name repair-utils \
  --zip-file fileb://layer.zip \
  --compatible-runtimes nodejs22.x \
  --compatible-architectures x86_64 \
  --query LayerVersionArn --output text
# Windows PowerShell, from an empty project folder
New-Item -ItemType Directory -Name nodejs
npm install --prefix nodejs lodash
Compress-Archive -Path .\nodejs -DestinationPath .\layer.zip
aws lambda publish-layer-version --layer-name repair-utils --zip-file fileb://layer.zip --compatible-runtimes nodejs22.x --compatible-architectures x86_64 --query LayerVersionArn --output text
// index.mjs in your function deployment package
import lodash from "lodash";
export const handler = async () => ({
  statusCode: 200,
  body: JSON.stringify({ result: lodash.camelCase("layer works") })
});
PartRequired condition
Handler packageindex.mjs at the function ZIP root
Layer ZIPnodejs/node_modules/lodash/...
Layer version ARNReturned by publish-layer-version; includes version number
Expected body{"result":"layerWorks"}

Attach the correct immutable layer version

If your new ZIP looks perfect but Lambda still cannot import the package, check the layer version ARN attached to the function. Publishing a layer with the same name creates a new version; it does not silently replace the one already in use. A function attached to version 3 continues using version 3 after you publish version 4.

The Lambda console lists attached layers on the function page. You can also ask the AWS CLI for Layers[].Arn in the function configuration. Each ordinary layer version ARN ends with its version number, making an old attachment straightforward to spot.

When attaching a new version through update-function-configuration, include all layer ARNs you intend to keep. The --layers argument represents the resulting layer list; passing only one ARN replaces the current list rather than appending it invisibly. Record the existing list before modifying a production function.

If you publish function versions and route traffic through an alias, inspect the configuration of the version the alias resolves to. Fixing $LATEST alone does not modify an already published function version. This is especially important when an alias serves production traffic while you test a newer configuration separately.

aws lambda get-function-configuration \
  --function-name repair-handler \
  --query "{Runtime:Runtime,Architecture:Architectures,Layers:Layers[].Arn}"

# Preserve any other needed layer ARNs:
aws lambda update-function-configuration \
  --function-name repair-handler \
  --layers arn:aws:lambda:us-east-1:123456789012:layer:repair-utils:4

Jake: "So a layer called repair-utils could be fixed in version four while my function still uses version three?"

Ethan: "Yes. The version number at the end of the attached ARN is what matters. Publishing a new one does not change your function automatically."

Inspect the real deployed layer instead of your source folder

When an archive has gone through CI/CD, the file on your laptop may no longer match the published artifact. Use get-layer-version-by-arn to retrieve metadata for the exact attached version and obtain a short-lived download URL. Download that archive, then list its contents before changing a single line of application code.

The download URL is temporary, so use it promptly and keep it out of public logs. The layer metadata also includes a content hash and archive size that help distinguish versions. A newly named build directory is not evidence that your function has received the new bytes.

You can inspect the running filesystem from a temporary diagnostic handler by listing /opt/nodejs/node_modules and logging process.env.NODE_PATH. This confirms what the execution environment actually sees. Keep such logging limited to development because large folder listings and environment details can expose unnecessary operational information.

If the published ZIP includes a package but the runtime still cannot load it, inspect the exact import name, package.json exports, and native binary compatibility next. If the ZIP lacks the package or has an extra folder level, resolve packaging first. This order saves you from mistaking a build pipeline problem for an IAM permissions problem.

aws lambda get-function-configuration \
  --function-name repair-handler --query "Layers[].Arn"
aws lambda get-layer-version-by-arn \
  --arn arn:aws:lambda:us-east-1:123456789012:layer:repair-utils:4 \
  --query "{URL:Content.Location,Size:Content.CodeSize,Hash:Content.CodeSha256}"
# Copy the temporary URL into a secure local download command,
# then inspect the downloaded ZIP:
unzip -l downloaded-layer.zip
// Temporary CommonJS diagnostic handler: index.cjs
const fs = require("node:fs");
exports.handler = async () => ({
  runtime: process.version,
  architecture: process.arch,
  path: process.env.NODE_PATH,
  folderExists: fs.existsSync("/opt/nodejs/node_modules/lodash"),
  resolved: require.resolve("lodash")
});

Tell missing packages apart from broken package exports

A package can physically exist under /opt and still fail to import. Node.js interprets package.json fields such as main, exports, and type to decide which files consumers can load. A wrong import path or an export that does not permit the requested entry point may therefore fail after Node.js finds the package directory.

A particularly confusing variant is ERR_PACKAGE_PATH_NOT_EXPORTED. That does not usually mean the whole package is missing; it means your code requested a subpath the package does not expose under its export rules. Import the supported public entry point instead of reaching into internal files.

An incomplete npm installation may also omit transitive dependencies required when the package starts. Scan the Require stack to see whether the failed require comes from your handler or a file under a library. Then verify your lockfile and installation command rather than inserting arbitrary files into the archive.

Package names are case sensitive on the Linux filesystem used by Lambda. Your development environment may not behave the same way. Compare the exact require() or import specifier with the actual directory and filenames in the published archive.

Choose the right CommonJS or ES-module import

If your handler uses require(), it is following the CommonJS module system. If it uses import, it is using ES-module syntax. A .mjs file is treated as an ES module, while a .cjs file is CommonJS; package.json with "type": "module" changes how .js files in that package scope are interpreted.

This distinction is separate from the ZIP root. A correctly placed layer can still fail if you call require() on a module published only for ESM under a runtime configuration that cannot handle that form. Conversely, converting the handler to ESM cannot rescue files packaged under an invisible extra parent directory.

For the simplest reproducible Lambda test, put index.mjs at the root of the function ZIP and use import lodash from "lodash". Keep the dependency in the layer at the documented path. That checks the managed runtime’s layer resolution without introducing an application-wide package type conversion.

When you change type, inspect files in both the function package and the layer package separately. The consuming project’s package.json does not automatically redefine every installed dependency’s own package scope. Prefer the package’s documented entry point, and leave third-party package.json files as they shipped.

// CommonJS function: index.cjs
const lodash = require("lodash");
exports.handler = async () => ({ result: lodash.camelCase("hello layer") });

// ES module function: index.mjs
import lodash from "lodash";
export const handler = async () => ({ result: lodash.camelCase("hello layer") });

// Example function package.json for .js ESM files:
// { "type": "module" }

Jake: "Does adding type module into my package.json solve every cannot-find-module message?"

Ethan: "No. It changes how JavaScript is interpreted. Your dependency must still live in a folder Node.js searches, and its export format must match your import."

Match native modules to Linux and CPU architecture

If a pure JavaScript package works but sharp, bcrypt, or another binary-backed dependency fails, inspect where that package was installed. Lambda runs on Amazon Linux, not Windows or macOS. A native addon compiled for your laptop can be present in the ZIP but unusable inside Lambda.

Your function’s architecture can be x86_64 or arm64. Native artifacts must target the architecture and operating-system environment used by the function, including appropriate library and runtime compatibility. The layer’s CompatibleArchitectures metadata helps filter choices, but metadata alone does not rebuild binary files.

For suitable packages, npm platform and architecture flags can help obtain Linux-compatible artifacts. Packages requiring compilation may need a Linux build environment matched to the Lambda runtime, often supplied through a container-based build. Keep the Node.js runtime major version aligned as well, especially for binary addons that depend on Node ABI details.

Errors may change from Cannot find module to failures loading a .node file, shared libraries, or an incorrect binary format. That change is useful evidence: the JavaScript package may now be found, while its native component is incompatible. Repackage native modules in the right environment instead of changing handler imports repeatedly.

aws lambda get-function-configuration --function-name repair-handler \
  --query "{Runtime:Runtime,Architectures:Architectures}"

# Example only: a Linux x86-64 sharp installation
npm install --prefix nodejs --platform=linux --arch=x64 sharp

Jake: "Why does lodash work but my image resizing package fail?"

Ethan: "Lodash is plain JavaScript. Image libraries often include native files that must match Linux, the processor architecture, and the runtime."

Check runtime and architecture settings before publishing

When you publish a layer, you can declare compatible runtimes and compatible architectures. These settings help the console present relevant versions and let you document the expected environment. They are not a guarantee that every binary inside the ZIP was built for the selected runtime or processor.

Use get-function-configuration to read the function’s Runtime and Architectures, then compare those values with the published layer metadata. If you have recently migrated from x86_64 to arm64, old native dependencies deserve immediate suspicion. If the function runtime changed, revisit module syntax and binaries compiled for the old version.

An unsupported or outdated runtime is a separate operational concern from a missing ZIP root. Upgrading the runtime is a blind fix for a layer that is demonstrably packaged incorrectly, so leave it alone for now. Make one change at a time, keep a rollback target, and verify an actual import after each change.

Check the Lambda runtimes page for what is generally available before you build. Preview runtimes can change under you and lack normal production support, so choose a generally available runtime for an ordinary production layer build.

Keep the Python folder rule separate from Node.js

Some people find this error while following a tutorial written for the wrong language. Python layers use a top-level python/ directory or a supported python/lib/python3.x/site-packages path, not nodejs/node_modules. Lambda places the content under /opt, and the Python runtime includes its corresponding paths in module lookup.

For Python, a usual build puts dependencies beneath python/ with pip, then zips the python folder at the archive root. If you copy the Node.js folder layout into a Python layer, import requests will not find the dependency in the expected Python search path. The reverse mistake causes Node.js module lookup failures.

Both language families share the same packaging principle: archive paths are relative to the ZIP root and are preserved under /opt. They differ in which subdirectories the language runtime searches. Decide which runtime actually executes the function before choosing the archive layout.

This article’s commands focus on Node.js. The Python comparison is here to prevent a common detour, not to suggest mixing Python and Node.js dependencies into one universal package. Keep platform- and runtime-specific layers easy to identify, version, and build.

python-layer.zip
└── python/
    └── requests/

# Node.js is different:
node-layer.zip
└── nodejs/
    └── node_modules/
        └── lodash/

Understand layer size and count limits without guessing

If your layer archive becomes large, distinguish the upload method from the execution quota. The current direct ZIP upload threshold is 50 MB, while a larger supported archive may be supplied using S3. That threshold is for the compressed transfer, not a promise that any uncompressed content will fit.

The combined unzipped size of the function deployment package and attached layers is limited to 250 MB for ZIP-based functions. A function can attach up to five layers. Splitting one 300 MB collection into several layers still counts against the combined unzipped limit.

For a concrete size example, a 35 MB unzipped handler package plus layers of 60 MB, 75 MB, and 40 MB totals 210 MB and is below the 250 MB combined ceiling. Add another 55 MB unzipped layer, and the total becomes 265 MB, exceeding that ceiling. Those numbers are illustrative package measurements, not prices or service charges.

If you need more space, examine dependencies that are not used at runtime, duplicate libraries, generated test fixtures, and architecture-specific files accidentally bundled together. Container-image Lambda functions use a different packaging model, and layers are not attached to them the same way. Choose that model deliberately rather than trying to force an oversized ZIP into layers.

Example componentUnzipped size
Function ZIP contents35 MB
Layer A60 MB
Layer B75 MB
Layer C40 MB
Combined unzipped210 MB: within 250 MB
Additional Layer D55 MB, making 265 MB: over limit

Jake: "Can I split a big layer into five little layers to make the limit disappear?"

Ethan: "You can attach up to five, but the combined unzipped function and layers still have a 250 MB ceiling. Splitting does not increase it."

Decide whether the AWS SDK belongs in your layer

Your Node.js Lambda runtime includes an AWS SDK for JavaScript v3, so a simple call using supported runtime-provided clients may not require its own SDK layer. That convenience can be useful for a small diagnostic function. It does not guarantee a particular SDK minor version remains fixed forever across runtime updates.

For production dependency control, bundle and pin the SDK packages your application needs in the function artifact or an intentional shared layer. This makes the dependency version part of your release rather than an invisible runtime assumption. It also helps reproduce a failure locally with the same dependencies.

Library lookup precedence matters if the SDK exists in more than one place. Dependencies in the function deployment package take precedence over dependencies supplied through layers, while layer copies can take precedence over runtime-included libraries. A surprising version can therefore load even when your layer contains the version you expected.

If you see Cannot find module 'aws-sdk' in code copied from older Node.js Lambda examples, check whether it expects the older v2 package. Modern managed Node.js runtimes include SDK v3 modules rather than treating that older import as universally available. Update the import or explicitly package the dependency your code uses.

// SDK v3 example (include a pinned package for reproducibility):
import { S3Client } from "@aws-sdk/client-s3";
const client = new S3Client({});

// An older v2-style example may fail without explicit packaging:
// const AWS = require("aws-sdk");

Find conflicts between function packages and multiple layers

If you attach a layer and the function keeps loading the old dependency behavior, inspect the function deployment ZIP. Files in /var/task/node_modules can take precedence over layer dependencies. Attaching a new layer does not necessarily override a package already bundled directly with the handler.

When several layers contain the same file path under /opt, they may conflict in the merged layer filesystem. Accidental overwrite behavior is a poor dependency-management strategy, so give each file one owner. Publish layers with distinct responsibilities and keep shared package ownership explicit.

Use a controlled diagnostic call to print the resolved module location, such as require.resolve("lodash") in a CommonJS handler. That tells you whether Node.js selected the function package or a layer path. A successful import alone does not always reveal which copy was loaded.

After identifying the selected copy, either remove the duplicate from the function build or intentionally keep it and document precedence. Consistency matters more than forcing every dependency into a layer. Some teams do better with a self-contained function ZIP, especially when only one function needs the package.

Share a layer with another AWS account safely

When another account needs your layer, publishing the archive in your account is only the first step. The owner grants access to a specific layer version through a resource-based policy. The consumer then attaches that version ARN to a function that can use it.

Use add-layer-version-permission with lambda:GetLayerVersion and the intended account ID as principal. Permissions are version-specific, so publishing a new version does not automatically copy the old version’s share policy. Repeat your explicit sharing process for each newly published version needed by the other account.

The ARN includes the AWS Region and account identifier. Match the layer Region to the function Region rather than assuming cross-account sharing also moves files between Regions. The consumer must use the published layer version and have the relevant permissions to attach it.

Keep the permission scope narrow. A public layer permission grants much broader access than a single-account permission, which may be inappropriate for proprietary libraries. Review the layer content before sharing because any permitted consumer can retrieve that version’s archive.

aws lambda add-layer-version-permission \
  --layer-name repair-utils \
  --version-number 4 \
  --statement-id permit-account-444455556666 \
  --action lambda:GetLayerVersion \
  --principal 444455556666

aws lambda get-layer-version-policy \
  --layer-name repair-utils --version-number 4

Jake: "If I share version four with my partner’s account, will version five work for them automatically?"

Ethan: "No. Layer sharing permissions are tied to individual versions. Grant access to the new version and update their function reference intentionally."

Use diagnostic logging without hiding the error

If the archive and layer version look correct, run a minimal diagnostic function rather than the entire application. A tiny handler that imports just one dependency isolates layer resolution from database calls, API Gateway mapping, and unrelated initialization logic. Keep the diagnostic test event simple.

Log the working Node.js version, process architecture, and relevant directory existence, but keep environment variables and secrets out of the dump. Use require.resolve for CommonJS or a small ESM import test to locate the selected package. A file existing in /opt and a package being importable are related but not identical findings.

CloudWatch logs can identify whether the failure occurs at initialization or later in the handler. Review the complete error class, message, and stack instead of searching only for the words Cannot find module. Distinguish a missing package from a bad export, a native shared-library problem, or missing file permissions.

Once the diagnosis is complete, remove temporary verbose filesystem listings and restore normal logging. A production function should retain useful error context without disclosing its internal dependency tree on every invocation. Keep the minimal diagnostic in a test fixture so the next layer release can be checked automatically.

Handle file permissions and missing transitive dependencies

If your package is visibly present yet Node.js cannot read a required file, check archive permissions. Lambda requires readable files and traversable directories in its Linux environment. Standard non-executable files commonly use permission mode 644, and directories or executable files use 755.

Permissions are particularly relevant when ZIP artifacts move between build systems or when an executable is bundled alongside JavaScript. A permission error usually has a different message from a straightforward module lookup failure. Keep that distinction in mind, or you will replace a healthy module when the operating system merely denied access.

Another failure mode is an incomplete node_modules tree. Some npm packages require separate runtime dependencies, and manually copying one package directory can leave those behind. Install dependencies through npm into the staging directory and use a lockfile when possible so the complete needed dependency tree is included.

Production-only installation can be appropriate, but confirm your build does not incorrectly classify runtime imports as development dependencies. A successful local test that had developer dependencies available is not proof that a production-only ZIP includes the same files. Inspect the staged archive rather than relying solely on the source repository.

chmod -R a+rX nodejs/
# Keep readable files and traversable directories before packaging.
zip -r layer.zip nodejs/

Build a release check that prevents the next bad layer

You can make this failure much rarer by checking archive paths automatically before publication. A build should reject a ZIP that lacks nodejs/node_modules or contains an unexpected top-level project directory. It should also record the package lockfile, runtime version, intended architecture, and resulting layer version ARN.

After publication, run a small test function or integration check against the new layer version before moving production traffic. A static ZIP listing proves packaging shape, but only an import inside the intended runtime demonstrates that module resolution and native dependencies agree. Keep both checks in your release process.

When deploying through infrastructure as code, update the function configuration reference to the newly published immutable layer ARN. Review plans for accidental removal of other attached layers. A CI build that publishes version 8 while the function remains on version 7 has not actually shipped the dependency change.

For shared layers, make a small compatibility matrix showing which runtime and architecture combinations you build and test. You can skip declaring every possible platform compatible merely because npm install completed. The record helps your team understand why one function succeeds while another using a different processor fails.

  1. Install dependencies from a committed lockfile into a clean staging directory.
  2. Inspect ZIP entries for the required nodejs/node_modules root.
  3. Build native dependencies for the function runtime and architecture.
  4. Publish a new immutable layer version and record its ARN.
  5. Attach that exact version in a development environment.
  6. Invoke an import-only test before promoting production traffic.

Know when a layer is the wrong packaging choice

If you are sharing a modest pure JavaScript library across several functions, a layer can reduce duplication in deployment workflows. If only one function uses the package, placing it directly inside the function ZIP may be simpler. Both approaches must use a predictable dependency build, but only the layer adds a second versioned artifact to manage.

For large dependency graphs or software that needs substantial operating-system packages, consider whether a Lambda container image fits your deployment workflow better. Container images have their own size rules and dependencies become part of the image. They skip separately attached Lambda layers, so the release and rollback model changes.

If your function already bundles its dependencies through a tool such as esbuild, inspect the bundle configuration first. A package configured as external may be expected at runtime, while a fully bundled package may not need a layer at all. Mixing the two patterns without clear ownership is a common way to ship missing imports.

Choose the approach whose runtime dependency graph you can inspect and reproduce. The most elegant shared dependency arrangement is not useful if every deployment requires guessing which artifact contains the module. A small, reliable function bundle often beats an unnecessary layer hierarchy.

Packaging methodBest fit
Function ZIPOne function owns its dependencies; simplest for smaller workloads
Shared Lambda layerSeveral ZIP functions consume a versioned common package
Container imageFunction ships with its OS libraries and dependencies; separate Lambda layers are not attached

Understand why a successful publish can still fail at invoke time

When you see a success message from PublishLayerVersion, interpret it as confirmation that the service stored an archive and recorded a new immutable layer version. It is not the equivalent of running npm, importing your package, or executing the handler. The upload interface does not know which module your application will request during the next invocation, so an archive with a misleading directory structure can pass publication and still fail initialization.

The gap is especially visible in multi-stage pipelines. One job prepares a dependency archive, another job publishes a layer version, and a third job updates function configuration. Each job can succeed independently while the overall application still points to a stale layer ARN or an incompatible module. The release is finished only when the target function successfully imports the intended package under the runtime and architecture that production uses.

If you use aliases to release Lambda versions gradually, test with the same qualifier that the application calls. An unqualified invocation may target $LATEST while a production alias still points to an older immutable function version. That older version can include its own layer references and will not inherit changes made to an unrelated configuration. Compare the alias routing target, function version, and layer ARN together before concluding that AWS ignored an update.

A useful release record includes the lockfile hash, ZIP checksum, published layer version ARN, function version, runtime identifier, architecture, and result of one import-only invocation. None of these details needs a long report; even a small machine-readable deployment manifest can make rollback and incident diagnosis less stressful. If the next release breaks, the record tells you which artifact changed instead of leaving you to reconstruct an evening of console clicks. Your team can also compare the release record against a new staging environment before routing customers to it. This is particularly useful when separate teams own the function ZIP and the shared dependency layer. A disagreement about which ARN is deployed becomes a simple configuration question rather than a late-night investigation of Node.js internals.

Recover when the first fix does not work

If you rebuilt the ZIP and attached a fresh version yet still see the same error, compare the actual resolved runtime configuration with the version ARN returned by AWS. Check aliases, Regions, architectures, and whether you are invoking a published version rather than $LATEST. Those mismatches can make a correct update appear ineffective.

Next, reproduce the failing import in the smallest possible handler. Start with a pure JavaScript package, then add the problematic package. If the pure JavaScript import succeeds and the native module fails, focus on the Linux artifact rather than the layer root. If neither works, revisit the ZIP and search path first.

For a support case, collect the sanitized CloudWatch error, request ID, runtime, architecture, function qualifier, attached layer ARNs, and the listing of the actual published ZIP. Include the import statement and expected module location. This gives support a focused reproducible description rather than an account of repeated blind rebuilds.

AWS Support can help clarify service behavior and troubleshoot supported integrations, but it cannot infer source files that were left out of your package or repair third-party native builds on your behalf. The practical fallback is to roll back to a known working function-and-layer combination while you diagnose the new artifact. Keep the previous immutable version available for that reason.

Jake: "What if none of this works and I need to get bookings running again?"

Ethan: "Roll back the function and layer combination that last worked. Then compare the published ZIP and runtime from the failed build without risking more customer requests."

Frequently asked questions about Lambda layer import errors

Why does my Lambda layer say Cannot find module?

The module is often missing from the layer ZIP search path, the wrong layer version is attached, or the package is incompatible with the runtime. Check that your ZIP starts with nodejs/node_modules and that the function references the intended version ARN. Then investigate package exports or native binaries.

What is the correct Node.js Lambda layer folder structure?

Use nodejs/node_modules/package-name at the root of the ZIP. Lambda extracts it beneath /opt, producing /opt/nodejs/node_modules/package-name. A supported runtime-specific nodejs/nodeXX/node_modules layout is another option.

Why is Runtime.ImportModuleError next to Cannot find module?

Runtime.ImportModuleError means the Node.js runtime could not load a required module while initializing the handler or its imports. The message can identify a missing dependency, bad path, or incompatible module. Read the full stack for the precise failed import.

How do I see which layer version my Lambda function uses?

Open the Lambda function and inspect the Layers section, or run aws lambda get-function-configuration and query Layers[].Arn. The ARN ends in a version number. Check the qualifier or alias used by production if it is not invoking $LATEST.

How can I see what is actually inside a deployed Lambda layer?

Run get-layer-version-by-arn for the exact attached ARN and retrieve its temporary Content.Location download URL. Download that ZIP and list its entries with unzip -l or a ZIP viewer. Inspect the ZIP root rather than trusting your local source directory.

What happens if I zip node_modules directly?

The archive can extract to /opt/node_modules instead of /opt/nodejs/node_modules. That is not the normal Node.js layer dependency path. Rebuild the archive with nodejs as its top-level folder.

Does publishing a new layer update existing functions automatically?

No. Layer versions are immutable, and publishing creates a new numbered version. Update the function configuration to refer to the new version ARN, preserving its other attached layers.

How many Lambda layers can I attach to one function?

A ZIP-based Lambda function can attach up to five layers. Its deployment package and all attached layers together must also fit the combined unzipped size quota. Adding layers does not increase that combined limit.

What are the AWS Lambda layer size limits?

A direct compressed ZIP upload has a 50 MB threshold, while larger supported archives can be uploaded through S3. The combined unzipped function and layers limit is 250 MB. These are separate constraints.

Do I need to install the AWS SDK in a Lambda layer?

Modern managed Node.js Lambda runtimes include the AWS SDK for JavaScript v3. For a reproducible pinned SDK version, package your required SDK modules with the function or an intentional layer. Older code using require("aws-sdk") may need migration or explicit v2 packaging.

Why does my Node.js layer work on x86_64 but fail on arm64?

Native dependencies can contain binaries built for a specific processor architecture. Check the Lambda function architecture and rebuild or install native packages for its Linux target. The layer metadata alone does not transform binary files.

Does package.json type module fix a Lambda layer import error?

The type module setting affects how .js files are treated as ES modules within their package scope. It can resolve module-format problems but cannot repair a missing dependency or wrong ZIP directory. Match require or import to the package export rules.

Can a Python layer use nodejs/node_modules?

A Python layer ordinarily uses a top-level python directory or a supported version-specific Python site-packages path. Node.js layers use nodejs/node_modules. Package for the runtime of the function you are actually deploying.

How do I share one Lambda layer with another AWS account?

Grant the target account lambda:GetLayerVersion through add-layer-version-permission on the specific layer version. The consumer attaches that version ARN in the same Region. New layer versions require their own sharing permission.

Why does Lambda import an old dependency even with a new layer?

The function deployment package can contain its own dependency copy that takes precedence over the layer. Production might also invoke a published function version tied to an older layer. Inspect resolved module paths and the exact function qualifier.

Can Lambda container image functions use Lambda layers?

Lambda layers attach to functions packaged as ZIP archives, not container-image functions. For a container image, package libraries into the image itself. Choose the packaging model that best fits your dependencies and release process.

Back at Jake’s shop, the fix is not a mysterious Node.js flag: his layer must have the correct archive root, his function must reference that published version, and the module must match the runtime that loads it. Once those three facts are visible, the remaining problems—package exports, architecture, and conflicting dependency copies—become manageable. I hope your next deployment goes directly to the confirmation screen; if the error remains, the exact module name and attached version ARN are the most useful clues to share.

📌 If you keep one line from this page

A Lambda layer works only when the installed module is in the runtime’s search path and the function uses the intended published version.

Revision note. Written October 15, 2026, with the five-layer and 250 MB limits and the Node.js 22 runtime in the examples. Measure twice, cut once: list the ZIP before you publish it.

Related