AWS Lambda fails on import because the file is treated as CommonJS
SyntaxError: Cannot use import statement outside a moduleShort answer
Lambda runs a .js file as CommonJS unless told otherwise, so import and export fail. Rename the file to .mjs or add type module to the package.json inside the deployment package, and keep the Handler setting in step with the file name. Or rewrite the file with require and exports.handler.
Fix it fast
1Find out which cause you have
Look at the file name and at the package.json in the function folder. They decide whether Node.js reads your file as CommonJS or as an ES module.
ls cat package.json2Match what you see, then jump to its fix
- 1
SyntaxError: Cannot use import statement outside a moduleThe file is index.js and no package.json says type moduleFix - 2
The error continues after renaming, or Lambda reports the handler cannot be foundThe Handler setting still names the old fileFix - 3
Some files in the project are .js with import, and you cannot rename or set typeYou want Lambda to pick the module type by itselfFix
- 1
What does the error look like?
SyntaxError: Cannot use import statement outside a module
Cause 1 of 3
The file is index.js and no package.json says type module
1Check
Node.js treats .js files as CommonJS by default. Only .mjs files, or .js files with type set to module in package.json, are ES modules.
grep -n '"type"' package.json2Fix
Rename the file to index.mjs, or set type to module in the package.json that ships with the function.
mv index.js index.mjs
# or, in package.json
{
"type": "module"
}3Verify
Deploy again and run a test event. The syntax error is gone.
node --check index.mjsConfirmed by docs.aws.amazon.com
Cause 2 of 3
The Handler setting still names the old file
1Check
The Handler value is the file name plus the exported function name. A rename needs no change when the name before the dot stays index, because Lambda looks for index.js or index.mjs, but a different file name needs an edit.
grep -n "export" *.mjs2Fix
In the console open Code, then Runtime settings, choose Edit, and set Handler to match, for example index.handler. Make sure the file exports a function with that name.
// index.mjs, matches Handler = index.handler
export const handler = async (event) => {
return { statusCode: 200, body: 'ok' };
};3Verify
Save the setting and run a test event.
node --input-type=module -e "import('./index.mjs').then(m => console.log(typeof m.handler))"Confirmed by docs.aws.amazon.com
Cause 3 of 3
You want Lambda to pick the module type by itself
1Check
On Node.js 22 and 24, Lambda turns off automatic detection of ES versus CommonJS by default. Look at the function's environment variables for NODE_OPTIONS.
aws lambda get-function-configuration --function-name my-function --query Environment.Variables2Fix
Re-enable detection by adding the flag to the NODE_OPTIONS environment variable. The update call replaces the whole variable set, so include your existing variables, or use the console under Configuration and Environment variables. The docs mark this as experimental, so renaming to .mjs is the safer fix.
aws lambda update-function-configuration --function-name my-function \
--environment "Variables={NODE_OPTIONS=--experimental-detect-module}"3Verify
Run a test event after the update finishes.
aws lambda get-function-configuration --function-name my-function --query LastUpdateStatusConfirmed by docs.aws.amazon.com
How do I stop it coming back?
- Pick one module style for the whole function and use the same one in tests and build scripts.
- Use .mjs for new Lambda code, as in the file the console creates for a new function.
- Bundle dependencies with the function instead of relying on whatever the runtime ships.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- Dispatch ProA real-time logistics platform: Flutter apps, Spring Boot services and a Kafka event pipeline on AWS.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Back end
API Gateway gives up on a slow Lambda or Node.js backend
$context.integrationErrorMessage in the access log shows the integration error
API Gateway stops waiting for the backend at its integration timeout: 29 seconds by default on REST APIs, a fixed 30 seconds on HTTP APIs.
4 causes, each with a fixBack end
Application Load Balancer returns 502 for a Node.js target
HTTPCode_ELB_502_Count
An ALB returns 502 when the target gives it something it cannot use: a refused or reset connection, a connection closed mid-request, a bad response, or a header over 32 K.
4 causes, each with a fixBack end
cdk synth says --app is required
--app is required either in command-line, in cdk.json or in ~/.cdk.json
The CDK CLI needs a command that runs your app and finds it in three places: the --app option, cdk.json in the project folder, or cdk.json in your home folder.
3 causes, each with a fixBack end
The AWS SDK in Node.js cannot find any credentials
Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1
The AWS SDK walks a fixed credential chain: code, environment variables, the shared files in ~/.aws, then role sources such as ECS or EC2.
3 causes, each with a fixBack end
AWS SDK for JavaScript v3 cannot find credentials, even for DynamoDB Local
A DynamoDB client pointed at http://localhost:8000 fails with the same message
The SDK walked its default credential provider chain and found nothing.
3 causes, each with a fixBack end
AWS SDK says the security token included in the request is invalid
The security token included in the request is invalid
The call reached AWS but the credentials it carried were refused.
3 causes, each with a fix