Lambda "require is not defined in ES module scope": Why index.mjs Breaks Your Code, the 2-Minute Rename, the Real Fix, and the Lambda-Only Setting

Logeshwaran
—

"ReferenceError: require is not defined in ES module scope, you can use import instead" means Node.js loaded your Lambda handler as an ES module, where require does not exist, while your code was written for CommonJS, where it does. The two fixes are a rename or a rewrite: rename the file to index.cjs (or remove "type": "module" from package.json) so Node treats it as CommonJS again, or switch every require to import and every exports.handler to export const handler. There is also a middle path, createRequire, for the one stubborn package. Here is the twist that sends people in circles: the same file can run on your laptop and fail on Lambda. Node.js 22 and 24 silently detect which module system a file uses; Lambda switches that detection off, so your ambiguous .js file is judged by its name and its package.json alone. This page explains what decides the module type, every version of the error and its mirror image, the three fixes with exact code, what happens to __dirname, JSON files and the AWS SDK, and the Lambda-only settings nobody tells you about.

Jake runs a phone repair shop, and his website has one small Lambda function that texts customers when a repair is ready. It had worked for a year. Last week his friend Ethan, a developer, helped him move it to the Node.js 24 runtime, created a fresh function in the console, pasted the old code in, and pressed Test. Red box: require is not defined in ES module scope. Jake's first question was reasonable: "I didn't change the code. Why does it suddenly not know what require is?" The answer is that the console had named the new file index.mjs, and that one letter changed which language Node thought it was reading. This page is the explanation Ethan gave him, with every fix they tried, in order of how little they change.

⚡ Quick Answer

• Why it happens → your file is .mjs, or your package.json has "type": "module", so Node runs it as an ES module and require is gone. What decides the module type.

• Fastest fix → rename index.mjs to index.cjs and set the handler to index.handler, or delete "type": "module". Fix 1.

• Best fix → convert to import and export const handler; Lambda recommends ES modules. Fix 2, with code.

• One package still needs require? → const require = createRequire(import.meta.url). Fix 3.

• Works locally, fails on Lambda? → Lambda disables Node's automatic module detection. The Lambda-only settings.

Every fix below works on the current Node.js 22, 24 and 26 runtimes. Node.js 18 and 20 are deprecated.

New to Lambda? Our plain-English guide to AWS Lambda explains functions, handlers and runtimes in ten minutes. You only need the word "handler" to follow this page: it is the function Lambda calls, and the error happens before Lambda ever reaches it.

🧭 NEW HERE? READ THESE FIRST

New to Lambda errors? These five pages make the rest of this one easy:

📌 Bookmark this; the module-type table and the three fixes cover every variant of this error you will meet.

Why Node says require is not defined: the two module systems

Node.js has two ways of organizing code into files, and they do not mix inside one file.

  • CommonJS is the older system. You load things with require() and share them with module.exports or exports.handler. Node wraps every CommonJS file in a function that provides five free variables: exports, require, module, __filename and __dirname.
  • ES modules are the standard JavaScript system. You load with import and share with export. None of those five variables exist. In their place you get import.meta, top-level await, and a stricter, static import rule.

The error is Node telling you, precisely, that it opened your file as an ES module and found a call to a variable that only CommonJS provides. It is not a missing package and not a Lambda bug. The full text is worth reading once, because it contains the fix: require is not defined in ES module scope, you can use import instead.

What decides which system Node uses

Node decides per file, by a short list of rules. Lambda follows the same rules. Here they are, in the order that matters:

Your fileNearest package.jsonTreated asrequire works?
index.mjsignoredES module, alwaysNo
index.cjsignoredCommonJS, alwaysYes
index.js"type": "module"ES moduleNo
index.js"type": "commonjs"CommonJSYes
index.jsno type field, or no package.jsonCommonJS on Lambda; on your laptop, Node 22+ may switch it to ES module if it sees import/export syntaxYes on Lambda

Two facts from that table explain nearly every report of this error:

  • The Lambda console creates index.mjs by default when you make a new Node.js function. Paste CommonJS code into it and you get this error on the first test. That was Jake's whole problem.
  • A package.json with "type": "module" flips every .js file in the package to ES modules, including files you did not write, such as a helper copied from an older project. Many starter templates and bundler configs add that line.

The same error in other clothes

Once you know the cause, the whole family of messages reads the same way:

  • ReferenceError: exports is not defined in ES module scope: your file is an ES module and uses exports.handler = .... Same cause, same fixes.
  • ReferenceError: module is not defined in ES module scope: the same, with module.exports.
  • ReferenceError: __dirname is not defined in ES module scope (or __filename): the same, and the section on __dirname has the replacement.
  • SyntaxError: Cannot use import statement outside a module: the mirror image. Your file is CommonJS and uses import. Rename it to .mjs, add "type": "module", or switch back to require.
  • Runtime.HandlerNotFound or Runtime.ImportModuleError: a cousin. Lambda could not find the file or the exported function the handler setting names, which happens when you rename index.mjs to index.cjs but leave the handler as something else, or export the function under a different name.

All of them appear in the console's test result and in the function's CloudWatch log group as the first line of the invocation. If you cannot find any log at all, our guide to Lambda not logging to CloudWatch fixes that first.

Which fix, when

Three fixes, each right for a different situation. Pick by how much you want to change today:

Your situationUseTimeWhat changes
Old working code, need it running tonightFix 1: rename to .cjs or drop "type": "module"Two minutesOne file name or one line of package.json
New function, or you own the codeFix 2: convert to import / exportTwenty minutes for a small functionEvery require and export line, plus __dirname and JSON
Converted, but one package only works with requireFix 3: createRequire for that packageTwo linesNothing else; delete the shim later
A helper file you cannot convert yetRename the helper to .cjs and import itOne renameES modules can import CommonJS files
Bundled with esbuild, webpack or TypeScriptMatch the output format to the extensionOne build settingThe build config, not the source

Fix 1: keep CommonJS, change the file's name (two minutes)

If the code is old, works, and you do not want to touch it today, tell Node it is CommonJS. Pick one of these; you do not need both.

  1. Rename the handler file from index.mjs to index.cjs. A .cjs file is always CommonJS, whatever package.json says. In the console editor, right-click the file to rename it; in a zip deployment, rename it before zipping.
  2. Or remove "type": "module" from package.json and keep the file as index.js. A .js file with no type field is CommonJS on Lambda.
  3. Check the handler setting. It is file.function, with no extension: index.handler works for index.js, index.mjs and index.cjs alike. If you renamed the file to handler.cjs, the setting becomes handler.handler. In the console it lives under Code, Runtime settings, Edit.
  4. Deploy and test. A CommonJS handler exports with exports.handler = async (event) => { ... }, exactly as the standard CommonJS example does.

This is the fix Ethan used first, at 6 p.m., to get Jake's texts flowing again. It is not the fix he left in place, for the reasons in the next section.

Fix 2: convert to ES modules (the long-term fix)

ES modules are the better long-term choice for Lambda, because they support top-level await, which lets you finish setup work, such as fetching a parameter or opening a database connection, during the initialization phase instead of on the first request. Our guide to Lambda cold starts explains why that matters for latency. The conversion is mechanical:

CommonJS (before)ES module (after)
const fs = require("fs");import fs from "node:fs";
const { S3Client } = require("@aws-sdk/client-s3");import { S3Client } from "@aws-sdk/client-s3";
const helper = require("./helper");import helper from "./helper.js"; (the extension is required)
const cfg = require("./config.json");import cfg from "./config.json" with { type: "json" };
exports.handler = async (event) => {}export const handler = async (event) => {}
module.exports = { handler, other }export { handler, other };
__dirname, __filenameimport.meta.dirname, import.meta.filename
require.resolve("x")import.meta.resolve("x")

Here is Jake's function after the conversion, in the standard ES module shape: imports at the top, a client created once outside the handler so it survives between invocations, and the handler exported by name.

// index.mjs
import { SNSClient, PublishCommand } from "@aws-sdk/client-sns";

const sns = new SNSClient({});

export const handler = async (event) => {
  const { phone, ticket } = JSON.parse(event.body ?? "{}");
  await sns.send(new PublishCommand({
    PhoneNumber: phone,
    Message: `Your repair ${ticket} is ready for pickup.`,
  }));
  return { statusCode: 200, body: JSON.stringify({ ok: true }) };
};

Four details catch people on the way across:

  • Relative imports need the extension. import x from "./helper" fails in ES modules; write "./helper.js". If the helper itself still uses require, rename it helper.cjs and import it; ES modules can import CommonJS files.
  • Imports are hoisted and static. You cannot put an import inside an if or a function. For a conditional load, use dynamic await import("./x.js"), which works in both systems.
  • Named exports from CommonJS packages may not destructure. If import { thing } from "old-package" fails, use import pkg from "old-package"; const { thing } = pkg;.
  • The handler must be exported by the name in the handler setting. export const handler matches index.handler. A default export does not.

Fix 3: keep one require with createRequire

Sometimes one dependency refuses to be imported: an old package that only works through require, or a config loaded by a path computed at runtime. Node's answer is createRequire, which builds a working require function inside an ES module:

// index.mjs
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);

const legacy = require("legacy-package");          // CommonJS-only dependency
const { DynamoDB } = require("@aws-sdk/client-dynamodb");

export const handler = async (event) => { /* ... */ };

Order matters. The two createRequire lines must come before any require(...) call. Put a require above them and you get a different error, Cannot access 'require' before initialization, which has sent more than one developer back to square one. Treat this as a bridge, not a destination: once the last stubborn package is replaced, delete the shim.

The Lambda-only settings: why it works on your laptop and fails in the cloud

This is the section that explains the "but it runs fine locally" reports. Recent Node.js versions added two conveniences, and Lambda switches both off, on purpose, for stability. From Lambda's Node.js documentation:

Node.js featureOn your laptopOn LambdaFlag Lambda appliesTo re-enable
Automatic detection of ES vs CommonJS in ambiguous .js filesOn by default since Node 22.7 and 20.19Off (Node.js 22, 24)--no-experimental-detect-moduleNODE_OPTIONS=--experimental-detect-module
require() of an ES moduleOn by default since Node 22.12 and 20.19; stable in 25.4Off (Node.js 20, 22, 24)--no-experimental-require-moduleNODE_OPTIONS=--experimental-require-module

What that means in practice:

  • A plain index.js with import statements and no "type" field runs on your Node 22 laptop, because Node notices the syntax and treats it as an ES module. On Lambda it fails with Cannot use import statement outside a module, because detection is off and the file is judged CommonJS by its name.
  • A CommonJS file that requires an ES-module-only package (.mjs, or "type": "module") works on Node 22.12 locally and fails on Lambda with an ES-module require error, because that feature is off too.

You can turn either feature back on by setting the environment variable NODE_OPTIONS to the re-enable flag; Lambda detects the override and removes its own disable flag. AWS attaches a warning worth repeating: functions that use experimental features are not covered by the Lambda SLA or by AWS Support. The dependable path is the one in this page's table: be explicit, with .mjs, .cjs or a "type" field, and never rely on detection.

The runtimes this applies to

Lambda's supported Node.js runtimes today are Node.js 22 (deprecation April 30, 2027), Node.js 24 (April 30, 2028) and Node.js 26, in public preview with general availability targeted for November 2026. Node.js 20 was deprecated on April 30, 2026 and Node.js 18 on September 1, 2025; both still run existing functions, but function creation and updates on them will be blocked in mid-2027. If you are reading this because a runtime upgrade broke a working function, you are in good company: the move from an old runtime, where a hand-made index.js was the norm, to a console-created index.mjs is the single most common trigger.

Reproduce Lambda's behavior on your laptop, and check what Lambda really deployed

Two short checks remove the guesswork, and both use only the CLI and Node.

Run Node with Lambda's own flags

Lambda disables two features with two Node flags, and you can pass the same flags locally. If the file fails this way on your machine, it will fail on Lambda; if it passes, the module type is settled:

node --no-experimental-detect-module --no-experimental-require-module -e "import('./index.mjs').then(m => console.log(Object.keys(m)))"

The output should list handler. An ES-module file with a stray require fails here with the same ReferenceError Lambda shows; a CommonJS file with a stray import fails with the SyntaxError. Swap the file name for ./index.cjs or ./index.js to test the other shapes, and run it from the folder that holds your package.json, because the nearest one decides what a .js file is.

Download what Lambda actually has

Deploy tools rename, bundle and sometimes add a package.json you never wrote. The only reliable view is the package Lambda holds:

# the handler setting and runtime Lambda is using
aws lambda get-function-configuration --function-name ready-text --query "[Runtime,Handler]"

# a temporary link to the deployed zip
aws lambda get-function --function-name ready-text --query "Code.Location" --output text

Download the zip from that link and list it. You are looking for three things: the handler file's real name and extension, whether a package.json sits next to it and what its type field says, and whether node_modules contains the packages you import. Half of the "I renamed it and it still fails" reports end here, with a build step that quietly renamed the file back.

__dirname, __filename, JSON files and the AWS SDK in an ES module

Once require is gone, three other CommonJS habits break in the same function. Each has a clean replacement.

__dirname and __filename

These two were never real globals; they were arguments of the CommonJS wrapper function. ES modules replace them with import.meta.dirname and import.meta.filename, available since Node 20.11 and 21.2, and marked stable in Node 22.16 and 24.0, so every current Lambda runtime has them:

import { readFile } from "node:fs/promises";
import { join } from "node:path";

const template = await readFile(join(import.meta.dirname, "templates", "ready.txt"), "utf8");

Notice the top-level await: in an ES module the file is read once, during initialization, not on every invocation. On Lambda your code lives under /var/task, so import.meta.dirname resolves there for the handler file. If you must support a very old Node, fileURLToPath(import.meta.url) from node:url gives the same path.

JSON files

require("./config.json") was a free JSON parser. In ES modules, use an import attribute, which is mandatory:

import config from "./config.json" with { type: "json" };

Only a default export is available; import { region } from "./config.json" does not work. AWS uses exactly this form in its own documentation to read the SDK version bundled in the runtime: import packageJson from '@aws-sdk/client-s3/package.json' with { type: 'json' };.

The AWS SDK: v3 is there, v2 is not

A related error appears the moment the module problem is solved: Cannot find package 'aws-sdk'. Every supported Node.js runtime includes a specific minor version of the AWS SDK for JavaScript v3, the modular @aws-sdk/client-* packages. The old monolithic aws-sdk v2 package is not part of the current runtimes. So import AWS from "aws-sdk" fails unless you bundle v2 yourself, and don't rely on the runtime copy of v3 either: include the clients you use in your deployment package, so a runtime update cannot change their version under you. The conversion is one import per service:

// v2, CommonJS (old)
const AWS = require("aws-sdk");
const s3 = new AWS.S3();
await s3.getObject({ Bucket, Key }).promise();

// v3, ES module (current)
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
const s3 = new S3Client({});
const res = await s3.send(new GetObjectCommand({ Bucket, Key }));
const text = await res.Body.transformToString();

To pin the version, run npm install @aws-sdk/client-s3 in the folder with your package.json and deploy node_modules with the function.

Layers, bundlers and frameworks: where the error hides

Lambda layers

A Node.js layer puts its packages at /opt/nodejs/node_modules, and CommonJS finds them through the NODE_PATH mechanism. The Node documentation is blunt about the other side: NODE_PATH is not part of resolving import specifiers. If a bare import such as import x from "x" stops working after you move a function to ES modules while the package lives in a layer, that is why. Two reliable options: bundle the dependency into the function package instead of the layer, or import it by its full path, import x from "/opt/nodejs/node_modules/x/index.js", which is ugly but explicit.

esbuild, webpack and TypeScript

Bundlers produce either CommonJS or ES-module output, and the output format must match what the file name and package.json promise. The classic trap is a bundler emitting ES-module syntax into a file called index.js in a package without "type": "module", which Lambda runs as CommonJS, or the reverse. Set the bundler's output format and the output extension together: ES-module format with .mjs, or CommonJS format with .cjs. TypeScript adds one more layer: the module setting in tsconfig.json decides what the compiler emits, and a .ts file compiled to CommonJS will still use require under the hood even if you wrote import.

SAM, CDK and Serverless Framework

Each framework names the handler for you, and each has an option for the output format when it bundles. If a deploy that used to work fails with this error after a framework upgrade, the usual cause is a changed default: the tool began emitting ES modules, or began naming files .mjs. Check the handler property and the generated file in the build folder before changing any source. When the handler property points at the wrong file after a rename, the error becomes Runtime.HandlerNotFound instead.

A real example: Jake's function, before and after

Here is the whole path Ethan took, in order, because the order is the point. Each step is reversible, and each one would have been enough on its own.

  1. Read the first log line. CloudWatch showed ReferenceError: require is not defined in ES module scope, you can use import instead at the top of the invocation, before any of Jake's own logging. That placed the failure at module load, not inside the handler.
  2. Look at the file name. The console had created index.mjs. The old function's file had been index.js with no package.json at all, which is CommonJS.
  3. Quick fix at 6 p.m. Rename to index.cjs, confirm the handler is still index.handler, deploy, test. Green. Customers got their texts that evening.
  4. Proper fix at the weekend. Convert the 40 lines to ES modules: the SNS import, export const handler, and the one JSON template file through an import attribute. Rename back to index.mjs.
  5. Move the setup out of the handler. With top-level await, the message template is read once at initialization. The cold start got a little faster, and the handler got shorter.
  6. Pin the SDK. npm install @aws-sdk/client-sns, so the runtime's bundled version no longer matters.

Before, the top of the file read:

const AWS = require("aws-sdk");
const fs = require("fs");
const path = require("path");
const template = fs.readFileSync(path.join(__dirname, "ready.txt"), "utf8");
const sns = new AWS.SNS();

exports.handler = async (event) => { /* ... */ };

After:

import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { SNSClient, PublishCommand } from "@aws-sdk/client-sns";

const template = await readFile(join(import.meta.dirname, "ready.txt"), "utf8");
const sns = new SNSClient({});

export const handler = async (event) => { /* ... */ };

Jake's review of the two versions: "The new one has fewer words and I can almost read it." Ethan took that as the highest praise available.

The mistakes that keep this error coming back

Pasting CommonJS into the console's index.mjs

The console's default file is an ES module. Either paste ES-module code, or rename the file to index.cjs before pasting.

Mixing both styles in one file

A file with import at the top and module.exports at the bottom fails in both systems, with one error or the other. Pick one per file.

Renaming the file but not the handler setting

index.mjs to index.cjs keeps index.handler valid. index.mjs to handler.cjs does not; update the handler to handler.handler or you trade this error for Runtime.HandlerNotFound.

Forgetting the extension in relative imports

import "./helper" fails in ES modules. Write "./helper.js", or "./helper.cjs" if the helper still uses require.

Putting createRequire below the first require

The shim must be defined before it is used, or Node reports "Cannot access 'require' before initialization."

A "type": "module" you did not know about

Templates and generators add it. If a working .js file breaks after you copy it into a new project, open the new project's package.json first.

Trusting a local test on Node 22 or 24

Your laptop auto-detects the module system in ambiguous files; Lambda does not. Make the file unambiguous and the two will agree.

Importing aws-sdk v2

The current runtimes ship SDK v3 only. Convert to @aws-sdk/client-*, or bundle v2 yourself, and in either case install the client in your package.

Expecting NODE_PATH to find layer packages from an ES module

ES modules do not consult NODE_PATH. Bundle the package with the function or import it by its full /opt path.

Using a default export for the handler

Lambda looks for the named export in the handler setting. export default async function is not index.handler.

Lambda "require is not defined in ES module scope": frequently asked questions

What does "require is not defined in ES module scope" mean in AWS Lambda?

Node.js loaded your handler file as an ES module, where require does not exist, because the file is .mjs or its package.json has "type": "module". Either make the file CommonJS again (rename to .cjs or remove the type field) or convert the code to import and export.

How do I fix require is not defined in Lambda?

The fastest fix is renaming index.mjs to index.cjs and keeping the handler as index.handler. The better fix is converting require to import and exports.handler to export const handler. For one stubborn package, use createRequire from node:module.

Why does the Lambda console create index.mjs?

Because Lambda recommends ES modules; they support top-level await, which lets setup work finish during initialization. A new Node.js function therefore starts as an ES module, and CommonJS code pasted into it fails until renamed or converted.

What is the difference between index.js, index.mjs and index.cjs in Lambda?

.mjs is always an ES module and .cjs is always CommonJS. .js follows the nearest package.json: "type": "module" makes it an ES module; no type field makes it CommonJS on Lambda, because Lambda disables Node's automatic detection.

What is "exports is not defined in ES module scope"?

The same problem with a different line: your ES module file uses exports.handler or module.exports. Replace it with export const handler, or rename the file to .cjs.

How do I use createRequire in a Lambda function?

At the very top of the .mjs file, add import { createRequire } from "node:module"; then const require = createRequire(import.meta.url);. Only then call require("package"). Placing a require above those two lines causes "Cannot access 'require' before initialization."

How do I get __dirname in a Lambda ES module?

Use import.meta.dirname, available on every current Lambda Node.js runtime, or fileURLToPath(import.meta.url) with path.dirname for older versions. On Lambda the handler's directory is /var/task.

How do I import a JSON file in a Lambda ES module?

Use an import attribute: import config from "./config.json" with { type: "json" };. The attribute is mandatory and only a default export is available.

Why does my function work locally but fail on Lambda with this error?

Node.js 22 and 24 auto-detect ES module syntax in ambiguous .js files; Lambda disables that detection with --no-experimental-detect-module. Make the file explicit with .mjs, .cjs or a "type" field, or set NODE_OPTIONS to --experimental-detect-module, which AWS does not cover under its SLA.

Can I require an ES module from a CommonJS Lambda function?

Not by default. Node 22.12 and later allow require of synchronous ES modules locally, but Lambda disables that feature on Node.js 20, 22 and 24. Use dynamic import() from the CommonJS file, or convert it, or re-enable the feature through NODE_OPTIONS at your own risk.

Why does Lambda say Cannot find package 'aws-sdk'?

Current Node.js runtimes include the AWS SDK for JavaScript v3 only, not the old aws-sdk v2 package. Import from @aws-sdk/client-s3 and the other modular clients, and install them in your deployment package.

What is "Cannot use import statement outside a module"?

The mirror image of this error: a CommonJS file contains import. Rename it to .mjs, add "type": "module" to package.json, or switch the file back to require.

Does the handler setting change when I rename index.mjs to index.cjs?

No. The handler is file name plus function name without the extension, so index.handler works for index.js, index.mjs and index.cjs. It changes only if the base name or the exported function name changes.

Can I use top-level await in a Lambda ES module?

Yes, and it is the right place for initialization work such as reading parameters or opening connections, so the work completes before the first invocation instead of during it.

Do Lambda layers work with ES modules?

Layer files are present at /opt/nodejs/node_modules, but ES modules do not use NODE_PATH to resolve bare imports. Bundle the package with the function or import it by its full /opt path.

Which Node.js runtimes does this apply to?

All current ones: Node.js 22 (deprecation April 30, 2027), Node.js 24 (April 30, 2028) and Node.js 26 in preview. Node.js 20 was deprecated on April 30, 2026 and Node.js 18 on September 1, 2025.

For readers preparing for an AWS certification

We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.

Exams that test this topic: Developer – Associate (DVA-C03 from December 1, 2026).

Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:

1. Why does a Node.js function fail with "require is not defined in ES module scope"?

The code runs as an ES module (a .mjs file or "type": "module" in package.json), which uses import instead of require.

2. How do you keep using require?

Use a .cjs file, or remove "type": "module".

3. How does the handler setting change for an ES module?

It points to the exported function in the .mjs file, such as index.handler.

4. How do you load the AWS SDK v3 in an ES module?

With named imports, such as import { S3Client } from "@aws-sdk/client-s3".

5. Can ES modules use top-level await in Lambda?

Yes, which helps initialize resources before the first invocation.

6. Which SDK version is included in current Node.js runtimes?

The AWS SDK for JavaScript v3.

Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.

πŸ“š ALSO READ

Where to go next, from the memory and timeout errors to the API Gateway 502 that often follows a fixed handler:

📌 Bookmark this; the module-type table settles every require-versus-import argument in one glance.

By the weekend, Jake's function was shorter, started faster, and was written in the form Lambda will keep supporting. The one-letter change that broke it, .js to .mjs, turned out to be the whole story, and the fix was to stop letting file names decide things quietly. "So I just tell it which one I mean," Jake said. That is the entire lesson, and it is a good one for more than Lambda.

📌 If you keep one line from this page

Be explicit: .mjs with import, or .cjs with require, and never let Lambda guess.

Rename to .cjs to get moving tonight; convert to ES modules when you have an hour; keep createRequire for the one package that refuses.

Revision note. Written October 9, 2026, from the Lambda Node.js documentation and the Node.js module references, with the runtime dates current as of that day. If a runtime upgrade broke a function that had worked for years, the rename fix gets you home tonight.

Related