(0 , core_1.default) is not a function on lambda handler using @middy/core

158 views Asked by At

I'm trying to use middy on my lambda middlewares, my stack is created with TypeScript with Serverless v3, Node.js v18.

There is the minimal reproductive example:

tsconfig.json:

{
  "compilerOptions": {
    "preserveConstEnums": true,
    "strictNullChecks": true,
    "sourceMap": true,
    "allowJs": true,
    "target": "es5",
    "module": "CommonJS",
    "outDir": ".build",
    "moduleResolution": "node",
    "esModuleInterop": false,
    "lib": ["es2015"],
    "rootDir": "./"
  }
}

package.json:

{
  "main": "handler.js",
  "dependencies": {
    "@middy/core": "^4.7.0",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "@types/lodash": "4.14.91",
    "@types/node": "^11.13.0",
    "serverless-offline": "^13.3.2",
    "serverless-plugin-typescript": "^1.1.7",
    "typescript": "^5.3.3"
  }
}

serverless.yml:

service: serverless-example

plugins:
  - serverless-plugin-typescript
  - serverless-offline

provider:
  name: aws
  runtime: nodejs18.x

functions:
  hello:
    handler: handler.handler
    events:
      - http:
          path: hello
          method: get

handler.ts

import middy from '@middy/core'

const myProtectedFunction= async (event, context) => {

  const userId = "123"
  return {
      statusCode: 200,
      body: JSON.stringify({ message: `Hello, user ${userId}!` }),
  };

};

export const handler = middy() .handler(myProtectedFunction);

After install serverless & dependencies just execute: serverless offline

and then make the request to the endpoint

Error image: error get

1

There are 1 answers

3
Bhavesh Parvatkar On BEST ANSWER

Here is what worked for me:

package.json

{
  "name": "s3-ts-1",
  "dependencies": {
    "@middy/core": "^4.7.0",
    "lodash": "^4.17.21"
  },
  "type": "module",
  "devDependencies": {
    "@types/lodash": "4.14.91",
    "@types/node": "^11.13.0",
    "serverless": "^3.38.0",
    "serverless-offline": "^13.3.2",
    "serverless-plugin-typescript": "^2.1.5",
    "typescript": "^5.3.3"
  }
}

Changes:

  • specify type
  • added serverless (this was because i have v2 in global scope, so added v3 in project scope)
  • updated the packages in dev dependencies

tsconfig.json

{
  "compilerOptions": {
    "preserveConstEnums": true,
    "strictNullChecks": true,
    "sourceMap": true,
    "allowJs": false,
    "target": "es2021",
    "outDir": ".build",
    "moduleResolution": "node",
    "lib": ["es2015"],
    "baseUrl": "./",
    "esModuleInterop": true,
    "typeRoots": ["node_modules/@types"],
    "resolveJsonModule": true
  }
}

Changes: I made some changes from the middy doc here

serverless.yml and handler.ts: No changes

Run command: npx sls offline (Because i added local dependency for v3. You might not need npx).