Lambda Layers
There are 2 common use cases for Lambda Layers. If your use case is not supported, feel free to open a new issue.
1. Packaging node_modules into a Layer
This covers the case where you have a package or file that you'd like to upload as a Lambda Layer.
Say you wanted to use the sharp package in your code and wanted to use the sharp Layer in your Lambda function when deployed.
Install the sharp package in your app.
npm install sharp
Create a layer folder in your app and copy the sharp layer to it.
mkdir -p layers/sharp
cd layers/sharpUnzip the packaged layer to this directory.
Configure your
sst.Function
to:- Set
sharp
as an external module, so it's not bundled in the Lambda code. - And, define a Layer pointing to
layers/sharp
(notlayers/sharp/nodejs
).
For example:
import * as lambda from "aws-cdk-lib/aws-lambda";
new sst.Function(stack, "Function", {
handler: "src/lambda.main",
nodejs: {
esbuild: {
external: ["sharp"],
},
},
layers: [
new lambda.LayerVersion(stack, "MyLayer", {
code: lambda.Code.fromAsset("layers/sharp"),
}),
],
});- Set
2. Use node_modules from an external Layer
On the other hand, there is the case where the Layer you want to use is already available in AWS.
Say you wanted to use the chrome-aws-lambda-layer that's already deployed to AWS. Along with the chrome-aws-lambda npm package.
Install the npm package.
npm install chrome-aws-lambda
Configure your
sst.Function
to:- Set
chrome-aws-lambda
as an external module, so it's not bundled in the Lambda function code. - And point to the existing Layer.
For example:
import * as lambda from "aws-cdk-lib/aws-lambda";
const layerArn =
"arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:22";
new sst.Function(stack, "Function", {
handler: "src/lambda.main",
nodejs: {
esbuild: {
external: ["chrome-aws-lambda"],
},
},
layers: [
lambda.LayerVersion.fromLayerVersionArn(stack, "ChromeLayer", layerArn),
],
});- Set
For further details, read the example on this use case and check out the sample SST app.