shou2017.com
JP

Run Lambda locally with serverless framework (node.js)

Wed Aug 19, 2020
Sat Aug 10, 2024
AWS

Environment

  • macOS Catalina
    • 10.15.4
  • serverless framework
    • Framework Core: 1.67.3 (standalone)
    • Plugin: 3.6.6
    • SDK: 2.3.0
  • node.js
    • v12.18.3
  • aws
    • aws-cli/1.18.0 Python/3.7.3 Darwin/19.4.0 botocore/1.15.0

Run Lambda locally

When developing Lambda with serverless framework, a very useful feature is AWS - Invoke Local.

With this, you can run your Lambda code locally.

As shown on the official site, you can run the following command:

serverless invoke local --function functionName

At first, this is enough, but in real development, you often use AWS Lambda Layers, so your folder structure might look like this:

-layer/nodejs/node_modules

-serverless.yml

With this structure, simply running serverless invoke local --function functionName will result in an error because npm in the layer can’t be referenced. You need to set up the path so the layer is referenced when running invoke local.

After some research, I found some people use symbolic links, but in my case, I wrote a script in package.json to handle it.

{
  "name": "serverless-framework-cli",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
		"local": "export NODE_PATH=\"layer/nodejs/node_modules\" && npx serverless invoke local --function changePassword"
  }
}

By doing this, you can simply run npm run local to execute Lambda locally.

Well, in my case, it’s possible because I manage Server Framewor and ESLint in the root directory which don’t need to be placed in the layer, but if everything is to be bundled in the layer, would it be better to use symbolic links?

See Also