Function

A replacement for the cdk.lambda.NodejsFunction that allows you to develop your Lambda functions locally. Supports ES and TypeScript out-of-the-box. It also applies a couple of defaults:

  • Sets the default memory setting to 1024MB.
  • Sets the default Lambda function timeout to 10 seconds.
  • Enables AWS X-Ray by default so you can trace your serverless applications.
  • AWS_NODEJS_CONNECTION_REUSE_ENABLED is turned on. Meaning that the Lambda function will automatically reuse TCP connections when working with the AWS SDK. Read more about this here.
  • Sets the IS_LOCAL environment variable for the Lambda function when it is invoked locally through the sst start command.

Initializer#

new Function(scope: Construct, id: string, props: FunctionProps)

Parameters

Examples#

Creating a Function#

import { Function } from "@serverless-stack/resources";
new Function(this, "MySnsLambda", {
handler: "src/sns/index.main",
});

Disabling bundling#

new Function(this, "MySnsLambda", {
bundle: false,
srcPath: "src/",
handler: "sns/index.main",
});

In this case, SST will zip the entire src/ directory for the Lambda function.

Configuring bundling#

new Function(this, "MySnsLambda", {
bundle: {
externalModules: ["fsevents"],
nodeModules: ["uuid"],
loader: {
".png": "dataurl",
},
copyFiles: [{ from: "public", to: "." }],
},
handler: "src/sns/index.main",
});

Setting additional props#

Use the cdk.lambda.FunctionOptions to set additional props.

new Function(this, "MyApiLambda", {
handler: "src/api.main",
timeout: 10,
environment: {
TABLE_NAME: "notes",
},
});

Handling a Dead Letter Queue#

const queue = new Queue(this, "MyDLQ");
new Function(this, "MyApiLambda", {
handler: "src/api.main",
deadLetterQueue: queue.sqsQueue,
});

Using SSM values as environment variables#

import { StringParameter } from "@aws-cdk/aws-ssm";
const apiKey = StringParameter.valueFromLookup(this, "my_api_key");
new Function(this, "MyApiLambda", {
handler: "src/api.main",
environment: {
API_KEY: apiKey,
},
});

The API_KEY environment variable can be accessed as process.env.API_KEY within the Lambda function.

Use the IS_LOCAL environment variable#

export async function main(event) {
return {
statusCode: 200,
headers: { "Content-Type": "text/plain" },
body: `Hello, World! Are we running locally: ${!!process.env.IS_LOCAL}`,
};
}

Properties#

Refer to the properties made available by cdk.lambda.Function.

Default Properties#

If you have properties that need to be applied to all the functions in your app, they can be set on the App construct using the setDefaultFunctionProps method.

Methods#

An instance of Function contains the following methods.

attachPermissions#

attachPermissions(permissions: Permissions)

Parameters

Attaches the given list of permissions to the function. This method makes it easy to control the permissions you want the function to have access to. It can range from complete access to all AWS resources, all the way to a specific permission for a resource.

Let's look at this in detail. Below are the many ways to attach permissions. Starting with the most permissive option.

Start with a simple function.

const fun = new Function(this, "Function", { handler: "src/lambda.main" });
  1. Giving full permissions

    fun.attachPermissions(PermissionType.ALL);

    This allows the function admin access to all resources.

  2. Access to a list of services

    fun.attachPermissions(["s3", "dynamodb"]);

    Specify a list of AWS resource types that this function has complete access to. Takes a list of strings.

  3. Access to a list of constructs

    import * as sns from "@aws-cdk/aws-sns";
    const sns = new sns.Topic(this, "Topic");
    const table = new Table(this, "Table");
    fun.attachPermissions([sns, table]);

    Specify which resource constructs you want to give complete access to. Currently supports:

    To add to this list, please open a new issue.

  4. Access to a list of specific permissions in a construct

    import * as dynamodb from "@aws-cdk/aws-dynamodb";
    const sns = new sns.Topic(this, "Topic");
    const table = new dynamodb.Table(this, "Table");
    fun.attachPermissions([
    [topic, "grantPublish"],
    [table, "grantReadData"],
    ]);

    Specify which permission in the construct you want to give access to. Specified as a tuple of construct and a grant permission function.

    CDK constructs have methods of the format grantX that allow you to grant specific permissions. So in the example above, the grant functions are: Topic.grantPublish and Table.grantReadData. The attachPermissions method, takes the construct and calls the grant permission function specified.

    Unlike option #3, this supports all the CDK constructs.

  5. A list of IAM policies

    import * as iam from "@aws-cdk/aws-iam";
    fun.attachPermissions([
    new iam.PolicyStatement({
    actions: ["s3:*"],
    effect: iam.Effect.ALLOW,
    resources: [
    bucket.bucketArn + "/private/${cognito-identity.amazonaws.com:sub}/*",
    ],
    }),
    new iam.PolicyStatement({
    actions: ["execute-api:Invoke"],
    effect: iam.Effect.ALLOW,
    resources: [
    `arn:aws:execute-api:${region}:${account}:${api.httpApiId}/*`,
    ],
    }),
    ]);

    The cdk.aws-iam.PolicyStatement allows you to craft granular IAM policies that you can attach to the function.

FunctionProps#

Takes the following construct props in addition to the cdk.lambda.FunctionOptions.

handler#

Type : string

Node.js runtime#

Path to the entry point and handler function. Uses the format, /path/to/file.function. Where the first part is the path to the file, followed by the name of the function that's exported in that file.

For example, if your handler file is in src/lambda.js and it exported a function called main. The handler would be src/lambda.main.

First checks for a .ts file and then for a .js file.

If the srcPath is set, then the path to the handler is relative to it. So if the srcPath is set to src. Then lambda.main as the handler would mean that the file is in src/lambda.js (or .ts).

Python runtime#

Path to the entry point and handler function relative to the srcPath. Uses the format, path/to/file.function. Where the first part is the path to the file, followed by the name of the function that's exported in that file.

For example, if your srcPath is src/, your handler file is in src/lambda.py, and it exported a function called main. The handler would be lambda.main.

Go runtime#

Path to the handler function. Uses the format, /path/to/file.go or just /path/to.

If the srcPath is set, then the path to the handler is relative to it. So if the srcPath is set to src. Then lambda.go as the handler would mean that the file is in src/lambda.go.

bundle?#

Type : boolean | FunctionBundleProps, defaults to true

Bundles your Lambda functions with esbuild. Turn this off if you have npm packages that cannot be bundled. Currently bundle cannot be disabled if the srcPath is set to the project root. Read more about this here.

If you wanted to configure the bundling process, you can pass in the FunctionBundleProps.

Only supported for the Node.js runtimes.

srcPath?#

Type : string, defaults to the project root

Node.js runtime#

The directory that needs to zipped up as the Lambda function package. Only applicable if the bundle option is set to false.

Note that for TypeScript functions, if the srcPath is not the project root, SST expects the tsconfig.json to be in this directory.

Python runtime#

For Python functions, srcPath is required. This is the directory where the requirements.txt, Pipfile, or poetry.lock is expected.

Note that for Python functions, you'll need to have Docker installed. While building and deploying, this construct will handle installing all the required modules in a Lambda compatible Docker container according to the runtime. This esnures that the Python Lambda functions are packaged correctly.

Go runtime#

The directory where go.mod is found.

memorySize?#

Type : number, defaults to 1024

The amount of memory in MB allocated to this function.

timeout?#

Type : number | cdk.core.Duration, defaults to 10

The function execution timeout in seconds. You can pass in the timeout as a number or as cdk.core.Duration.

runtime?#

Type : string | cdk.lambda.Runtime, defaults to nodejs12.x

The runtime environment. You can pass in the runtime as a string or as cdk.lambda.Runtime. Only runtimes of the Node.js, Go, and Python family are supported.

tracing?#

Type : cdk.lambda.Tracing, defaults to cdk.lambda.Tracing.ACTIVE

Turns on AWS X-RAY for the Lambda function, to enable tracing.

permissions?#

Type : Permissions, defaults to cdk.lambda.Tracing.ACTIVE

Attaches the given list of permissions to the function. Configuring this property is equivalent to calling attachPermissions after the function is created.

FunctionDefinition#

Type : string | Function | FunctionProps

All the high-level SST constructs that create a function internally accepts this as a type. So you can define a function by passing in the handler as a string:

"src/create.main"

Or the FunctionProps:

{
bundle: false,
srcPath: "src/",
handler: "sns/index.main",
}

Or an instance of the Function itself.

new Function(this, "Create", {
handler: "src/create.main",
});

FunctionBundleProps#

loader?#

Type : { [string]: esbuild.Loader }, defaults to {}

Use loaders to change how a given input file is interpreted.

Configuring a loader for a given file type lets you load that file type with an import statement or a require call.

externalModules?#

Type : string[], defaults to ['aws-sdk']

A list of modules that should be considered as externals. This usually applies to ones that are already available in the runtime or are provided separately as a Lambda Layer.

nodeModules?#

Type : string[], defaults to all modules are bundled

A list of modules that should be installed instead of bundled.

copyFiles?#

Type : FunctionBundleCopyFilesProps[], defaults to []

FunctionBundleCopyFilesProps#

from#

Type : string

The path to the file or folder relative to the srcPath.

to#

Type : string

The path in the Lambda function package the file or folder to be copied to.