🌐
AWS re:Post
repost.aws › questions › QURW2yK1m5QuWW3vy6W5d1Yg › referenceerror-with-lambda-function-errormessage-require-is-not-defined-in-es-module-scope
ReferenceError with lambda function : "errorMessage": "require is not defined in ES module scope | AWS re:Post
February 21, 2024 - This is why the error suggests using import instead of require(). To resolve this issue, you need to conform to the ES module syntax for imports: import AWS from 'aws-sdk'; const s3 = new AWS.S3();
🌐
GitHub
github.com › aws-powertools › powertools-lambda-typescript › issues › 2464
Bug: require() command in ES module, stopping lambda from running · Issue #2464 · aws-powertools/powertools-lambda-typescript
May 1, 2024 - "ReferenceError: require is not defined in ES module scope, you can use import instead", Within the function ProviderService.captureHTTPsGlobal a require statement in included, which halts ES modules.
Author   Jimmy89
🌐
GitHub
github.com › aws-amplify › amplify-cli › issues › 13494
Try to run ES module in a lambda function · Issue #13494 · aws-amplify/amplify-cli
December 20, 2023 - To treat it as a CommonJS script, rename it to use the '.cjs' file extension.", "stack": [ "ReferenceError: require is not defined in ES module scope, you can use import instead", "This file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\".
Author   loic-thomas
🌐
Pipedream
pipedream.com › help
What is the solution to the 'require is not defined in es module scope' error? - Help - Pipedream
March 26, 2023 - This topic was automatically generated from Slack. You can find the original thread here. hello everyone, i am getting an error: referenceerror: require is not defined in es module scope, you can use import instead ca…
🌐
GitHub
github.com › serverless › serverless › issues › 12118
Node ES6 support issue · Issue #12118 · serverless/serverless
August 17, 2023 - When not setting type: module in package.json Lambda complains about using import statements outside of the module.export · SyntaxError: Cannot use import statement outside a module · But when I do set the type to module in package.json it complains that I am using required. Which I am not doing, but the s_tag_file.js file which is created by Serverless does contain required · { "errorType": "ReferenceError", "errorMessage": "require is not defined in ES module scope, you can use import instead\nThis file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\".
Author   nickhaakman
🌐
GitHub
github.com › aws-powertools › powertools-lambda-typescript › issues › 2605
Bug: ReferenceError: require is not defined in ES module scope when using @aws-lambda-powertools/tracer in ES Module · Issue #2605 · aws-powertools/powertools-lambda-typescript
June 5, 2024 - I'm encountering an issue when trying to use the @aws-lambda-powertools/tracer package in a TypeScript project configured as an ES module. The error message suggests that there is an internal use of require which is not supported in ES module scope.
Author   william-mens
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 76523086 › how-do-i-resolve-require-is-not-defined-in-es-module-scope-you-can-use-import
amazon web services - how do I resolve 'require is not defined in ES module scope, you can use import instead'? on AWS Lambda - Stack Overflow
import { Pool, Client } from 'pg' const pool = new Pool({ user: 'postgres', host: 'tom-practice-database-2.csl0vrlucjal.eu-west-2.rds.amazonaws.com', database: 'tom-practice-database-2', password: 'root4322', port: 5432, }) exports.handler = async(event) => { pool.connect() await pool.query('SELECT * FROM employees') .then((res) => console.log(res)) .catch(console.log) return { statusCode: 200, body: JSON.stringify('Hello from lambda') } }; ... { "errorType": "ReferenceError", "errorMessage": "require is not defined in ES module scope, you can use import instead", "trace": [ "ReferenceError: require is not defined in ES module scope, you can use import instead", " at file:///var/task/index.mjs:2:28", " at ModuleJob.run (node:internal/modules/esm/module_job:194:25)" ] }
🌐
Oscarchou
oscarchou.com › posts › [lambda/nodejs] lambda stop working after updating to node.js 20
[Lambda/NodeJS] Lambda Stop Working After Updating to Node.js 20 | Oscar's Notebook
October 12, 2024 - This is because Node.js 20.x uses ECMAScript modules (ESM) by default. You need to update your code to use import instead of require. The below code snippet is an example of reading message from SQS queue.
Top answer
1 of 5
23

To upgrade to Node.js 18, you have to change the code to make the function work again. I don't use zip files, config files or layers.

Steps to upgrade your AWS Lambda function:

1. Change the filename of index.js to index.mjs

File names ending in .mjs are always treated as ES modules. File names ending in .js inherit their type from the package.

Reference: https://aws.amazon.com/blogs/compute/using-node-js-es-modules-and-top-level-await-in-aws-lambda/

You should rename your index.js file to index.mjs to prevent one of the following errors:

  • SyntaxError: Cannot use import statement outside a module

  • SyntaxError: Unexpected token 'export'

2. Change your handler from CommonJS module handler to ES module handler

You must update the way you define your handler to prevent one of the following errors:

  • Runtime.HandlerNotFound: index.handler is undefined or not exported

  • ReferenceError: exports is not defined in ES module scope

Reference: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html

// Before NodeJS 18
exports.handler = async function (event, context) {
  console.log("EVENT: \n" + JSON.stringify(event, null, 2));
  return context.logStreamName;
}; 

// NodeJS 18 and above
export const handler = async (event, context) => {
  console.log("EVENT: \n" + JSON.stringify(event, null, 2));
  return context.logStreamName;
};

3. Change the way you import your modules

You cannot use the "require" keyword anymore. You will get the following error when you do:

  • ReferenceError: require is not defined in ES module scope, you can use import instead

It is important to know that since NodeJS 18 you cannot import the complete AWS SDK anymore, but you have to specify which modules you need, or you will get the following error:

  • Runtime.ImportModuleError: Error: Cannot find module 'aws-sdk'

Reference: https://aws.amazon.com/blogs/compute/node-js-18-x-runtime-now-available-in-aws-lambda/

// Before NodeJS 18
const AWS = require("aws-sdk");
const https = require("https");
const querystring = require("querystring"); 

// NodeJS 18 and above. In this example the module "client-sns" is imported from the AWS SDK.
import * as AWS from "@aws-sdk/client-sns";
import https from "https";
import querystring from "querystring";
2 of 5
17

In order to fix the error, you could opt to use at least NodeJS version 18 or the latest runtime version (NodeJS 22)

  1. You can upgrade your old functions by adding "type": "module" to your package.json file. This will inform the Node runtime to use ES6 modules instead of the traditional ES5/CommonJS syntax.

  2. Change the extension of your files to .mjs to force the NodeJS runtime to treat your file as an ES6 module.

  3. If you are using esbuild, you will have to make sure that your build output is compatible with the ES6 modules (import/export).

  4. If you were using TypeScript, configure your transpiler to produce a build output that is compatible with ES modules.

  5. If there is a performance issue, it would be minimal that we don't have to worry about it! PS: I recommend to test the compatibility of the ES5/CJS/CommonJS modules that the lambda uses when you change the runtime.

🌐
Medium
sig03.medium.com › aws-lambda에서-node로-api-호출-시-에러-require-is-not-defined-in-es-module-scope-you-can-use-import-af31c36563d2
AWS Lambda에서 Node로 api 호출 시 에러: require is not defined in ES module scope, you can use import instead | by sig03 | Medium
February 16, 2023 - AWS Lambda에서 Node로 api 호출 시 에러: require is not defined in ES module scope, you can use import instead 개요 lambda에서 node로 api 호출하는 예제를 만듦 기존의 예제를 …
🌐
Stack Overflow
stackoverflow.com › questions › 77789021 › aws-pre-signup-lambda-function-referenceerror-require-is-not-defined-in-es-mo
amazon web services - AWS pre-signup lambda function - ReferenceError: require is not defined in ES module scope, you can use import instead - Stack Overflow
January 9, 2024 - The only difference from the tutorial is that I'm not using the node-fetch module, but rather the native fetch function since I'm using Node v18 (like suggested in this official AWS Amplify documentation and confirmed by the line "Runtime": "nodejs18.x" inside the /amplify/backend/function/<my_function_name>/...-cloudformation-template.json) But when this lambda function gets called, I get this error: { "errorType": "ReferenceError", "errorMessage": "require is not defined in ES module scope, you can use import instead\nThis file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\".
🌐
GitHub
github.com › webpack › webpack › issues › 18580
Require is not defined in ES module scope, you can use import instead · Issue #18580 · webpack/webpack
July 15, 2024 - What is the current behavior? build is getting failed. ReferenceError: require is not defined in ES module scope, you can use import instead
Author   PriyaBangar
🌐
AWS
aws.amazon.com › blogs › compute › using-node-js-es-modules-and-top-level-await-in-aws-lambda
Using Node.js ES modules and top-level await in AWS Lambda | Amazon Web Services
January 6, 2022 - Consider a Lambda function that retrieves a parameter from the AWS Systems Manager Parameter Store. Previously, using CommonJS syntax, you place the await operator in the body of the handler function: // method1 – CommonJS // CommonJS require syntax const { SSMClient, GetParameterCommand } = require("@aws-sdk/client-ssm"); const ssmClient = new SSMClient(); const input = { "Name": "/configItem" }; const command = new GetParameterCommand(input); const init_promise = ssmClient.send(command); exports.handler = async () => { const parameter = await init_promise; // await inside handler console.log(parameter); const response = { "statusCode": 200, "body": parameter.Parameter.Value }; return response; };