Lambda Layers
Amplify offers the ability to add layers to your functions which contain your library dependencies. Lambda layers allow you to separate your function code from its dependencies, enabling easier management of shared components across multiple functions and reducing deployment package sizes.
To add a Lambda layer to your function, follow these steps:
-
First, create and set up your Lambda layer in AWS. You can do this through the AWS Console or using the AWS CLI. For guidance on creating layers, refer to the AWS documentation on creating Lambda layers.
-
Once your layer is created and available in AWS, you can reference it in your Amplify project as shown below.
Specify the
layers
property indefineFunction
, for example:amplify/functions/my-function/resource.tsimport { defineFunction } from "@aws-amplify/backend";export const myFunction = defineFunction({name: "my-function",layers: {"@aws-lambda-powertools/logger":"arn:aws:lambda:us-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:12",},});The Lambda layer is represented by an object of key/value pairs where the key is the module name that is exported from your layer and the value is the ARN of the layer. The key (module name) is used to externalize the module dependency so it doesn't get bundled with your lambda function. A maximum of 5 layers can be attached to a function, and they must be in the same region as the function.
-
Then use the locally installed module in the function handler:
amplify/functions/my-function/handler.tsimport { Logger } from "@aws-lambda-powertools/logger";import type { Handler } from "aws-lambda";const logger = new Logger({ serviceName: "serverlessAirline" });export const handler: Handler = async (event, context) => {logger.info("Hello World");};
For further information on creating and managing your layers refer to AWS documentation for Lambda layers