Skip to content
v2.276.0

WebFunction L2 construct Added in v2.276.0 ​

A Lambda WebFunction L2 construct.

Creates a WebFunction with a revision and endpoint for serving HTTP traffic.

Example ​

ts
import * as s3 from 'aws-cdk-lib/aws-s3';

declare const codeBucket: s3.IBucket;

new lambda.WebFunction(this, 'PerRegionApi', {
  code: lambda.WebFunctionCode.fromBucket(codeBucket, 'app.zip', 'version-id'),
  runtime: lambda.WebFunctionRuntime.NODEJS_24_X,
  defaultEndpointAuth: lambda.WebFunctionAuthType.IAM_AUTH,
  defaultEndpoint: {
    endpointLocation: lambda.WebFunctionEndpointLocation.perRegion(['us-east-1', 'us-west-2']),
  },
});
python
import aws_cdk.aws_s3 as s3

# code_bucket: s3.IBucket


lambda_.WebFunction(self, "PerRegionApi",
    code=lambda_.WebFunctionCode.from_bucket(code_bucket, "app.zip", "version-id"),
    runtime=lambda_.WebFunctionRuntime.NODEJS_24_X,
    default_endpoint_auth=lambda_.WebFunctionAuthType.IAM_AUTH,
    default_endpoint=lambda.WebFunctionDefaultEndpointOptions(
        endpoint_location=lambda_.WebFunctionEndpointLocation.per_region(["us-east-1", "us-west-2"])
    )
)
java
import software.amazon.awscdk.services.s3.*;

IBucket codeBucket;


WebFunction.Builder.create(this, "PerRegionApi")
        .code(WebFunctionCode.fromBucket(codeBucket, "app.zip", "version-id"))
        .runtime(WebFunctionRuntime.NODEJS_24_X)
        .defaultEndpointAuth(WebFunctionAuthType.IAM_AUTH)
        .defaultEndpoint(WebFunctionDefaultEndpointOptions.builder()
                .endpointLocation(WebFunctionEndpointLocation.perRegion(List.of("us-east-1", "us-west-2")))
                .build())
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AWS.S3;

IBucket codeBucket;


new WebFunction(this, "PerRegionApi", new WebFunctionProps {
    Code = WebFunctionCode.FromBucket(codeBucket, "app.zip", "version-id"),
    Runtime = WebFunctionRuntime.NODEJS_24_X,
    DefaultEndpointAuth = WebFunctionAuthType.IAM_AUTH,
    DefaultEndpoint = new WebFunctionDefaultEndpointOptions {
        EndpointLocation = WebFunctionEndpointLocation.PerRegion(new [] { "us-east-1", "us-west-2" })
    }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import s3 "github.com/aws/aws-cdk-go/awscdk"

var codeBucket IBucket


lambda.NewWebFunction(this, jsii.String("PerRegionApi"), &WebFunctionProps{
	Code: lambda.WebFunctionCode_FromBucket(codeBucket, jsii.String("app.zip"), jsii.String("version-id")),
	Runtime: lambda.WebFunctionRuntime_NODEJS_24_X(),
	DefaultEndpointAuth: lambda.WebFunctionAuthType_IAM_AUTH,
	DefaultEndpoint: &WebFunctionDefaultEndpointOptions{
		EndpointLocation: lambda.WebFunctionEndpointLocation_PerRegion([]*string{
			jsii.String("us-east-1"),
			jsii.String("us-west-2"),
		}),
	},
})

Initializer ​

ts
new WebFunction(scope: Construct, id: string, props: WebFunctionProps)
python
WebFunction(scope: Construct, id: str, props: WebFunctionProps)
java
new WebFunction(Construct scope, String id, WebFunctionProps props)
csharp
new WebFunction(Construct scope, string id, WebFunctionProps props)
go
NewWebFunction(Scope Construct, Id *string, Props WebFunctionProps)

Construct Props ​

applicationLogLeveloptionalApplicationLogLevelapplication_log_leveloptionalApplicationLogLevelapplicationLogLeveloptionalApplicationLogLevelApplicationLogLeveloptionalApplicationLogLevelApplicationLogLeveloptionalApplicationLogLevel#
The minimum log level for application logs (logs emitted by your code, e.g. `console.log()`, `console.warn()`). Only logs at this level or above will be captured in CloudWatch.

Default: No application log level filtering.

For example, setting this to INFO will capture console.info() and console.warn() but filter out console.debug().

The deployment package for the WebFunction.
defaultEndpointoptionalWebFunctionDefaultEndpointOptionsdefault_endpointoptionalWebFunctionDefaultEndpointOptionsdefaultEndpointoptionalWebFunctionDefaultEndpointOptionsDefaultEndpointoptionalWebFunctionDefaultEndpointOptionsDefaultEndpointoptionalWebFunctionDefaultEndpointOptions#
The other settings of the endpoint the WebFunction creates, `endpoint`.

Default: a home-Region endpoint named prod, with no description and no scaling or rate limit beyond your account's quotas

Endpoints added with addEndpoint() take their own settings, auth type included.

defaultEndpointAuthWebFunctionAuthTypedefault_endpoint_authWebFunctionAuthTypedefaultEndpointAuthWebFunctionAuthTypeDefaultEndpointAuthWebFunctionAuthTypeDefaultEndpointAuthWebFunctionAuthTyperequired#
The authentication type of the endpoint the WebFunction creates, `endpoint`.
notes

There is no default: you must choose explicitly so an endpoint is never accidentally public or accidentally locked down. Specify WebFunctionAuthType.IAM_AUTH (Lambda authorizes requests with SigV4/IAM) or WebFunctionAuthType.APPLICATION_MANAGED (the endpoint is public and your function handles authorization).

With IAM_AUTH, requests must be signed with SigV4 and carry the X-Amz-Content-SHA256 header, also for a request without a body; without it the endpoint returns 403 even for a valid signature. A MULTI_REGION endpoint is signed with SigV4a, for the Region set *.

egressNetworkConnectoroptionalINetworkConnectoregress_network_connectoroptionalINetworkConnectoregressNetworkConnectoroptionalINetworkConnectorEgressNetworkConnectoroptionalINetworkConnectorEgressNetworkConnectoroptionalINetworkConnector#
The network connector that gives the function egress into a VPC.

Default: no VPC egress

notes

The revision pins to the connector's latest version at the time it is created. For a connector defined in the same stack, every update to the connector therefore replaces the revision as part of that deployment, and traffic moves to the new version with it. To hold the function on a fixed version instead — or to use a connector from another stack, whose changing version cannot be exported — import the version with NetworkConnector.fromNetworkConnectorVersionArn().

The connector must have been created for NetworkConnectorComputeType.WEB_FUNCTION, and the endpoint must be WebFunctionEndpointType.HOME_REGION.

The full INetworkConnector is required (rather than a ref) because the revision pins to latestVersionArn, which INetworkConnectorRef does not carry.

[disable-awslint:prefer-ref-interface]

entryPointoptionalstringentry_pointoptionalstrentryPointoptionalStringEntryPointoptionalstringEntryPointoptional*string#
The entry file the runtime executes, relative to the root of the deployment package.

Default: the runtime's default entry point, index.js

Only supported for Node.js runtimes. When set, it is passed to the runtime via the reserved AWS_LAMBDA_NODEJS_ENTRYPOINT environment variable. Do not set that variable through environment as well.

environmentoptional{ [key: string]: string }environmentoptionaltyping.Mapping[str, str]environmentoptionalMap<String, String>EnvironmentoptionalIDictionary<string, string>Environmentoptional*map[string]*string#
Key-value pairs of environment variables to pass to the WebFunction.

Default: No environment variables.

kmsKeyoptionalIKeyRefkms_keyoptionalIKeyRefkmsKeyoptionalIKeyRefKmsKeyoptionalIKeyRefKmsKeyoptionalIKeyRef#
The KMS key used to encrypt environment variables.

Default: AWS managed key.

The Lambda service principal is granted the key usage it needs to encrypt and decrypt the revision's environment variables.

logGroupoptionalILogGroupReflog_groupoptionalILogGroupReflogGroupoptionalILogGroupRefLogGroupoptionalILogGroupRefLogGroupoptionalILogGroupRef#
The CloudWatch log group to send logs to.

Default: A log group is created, named by CloudFormation and retained when the stack is deleted. Read its name from the logGroup attribute.

maxConcurrencyPerEnvironmentoptionalnumbermax_concurrency_per_environmentoptionalint | floatmaxConcurrencyPerEnvironmentoptionalNumberMaxConcurrencyPerEnvironmentoptionaldoubleMaxConcurrencyPerEnvironmentoptional*float64#
The maximum number of concurrent requests handled by a single execution environment.

Default: the service default of 64 is applied

Must be an integer between 1 and 128. When omitted, nothing is sent and the service applies its default.

revisionDescriptionoptionalstringrevision_descriptionoptionalstrrevisionDescriptionoptionalStringRevisionDescriptionoptionalstringRevisionDescriptionoptional*string#
A description of the WebFunction revision.

Default: No description.

Must be 256 characters or fewer.

roleoptionalanyroleoptionalanyroleoptionalanyRoleoptionalanyRoleoptionalany#
The IAM execution role for the WebFunction.

Default: A new role with AWSLambdaBasicExecutionRole is created.

The runtime environment for the WebFunction.
systemLogLeveloptionalSystemLogLevelsystem_log_leveloptionalSystemLogLevelsystemLogLeveloptionalSystemLogLevelSystemLogLeveloptionalSystemLogLevelSystemLogLeveloptionalSystemLogLevel#
The minimum log level for system logs (logs emitted by the Lambda runtime, e.g. start/end/report lines and runtime errors). Only logs at this level or above will be captured in CloudWatch.

Default: No system log level filtering.

tagsoptional{ [key: string]: string }tagsoptionaltyping.Mapping[str, str]tagsoptionalMap<String, String>TagsoptionalIDictionary<string, string>Tagsoptional*map[string]*string#
Tags to apply to the WebFunction.

Default: No tags.

Only the WebFunction resource carries tags. Its revision and endpoint are not taggable, so nothing is applied to them.

timeoutoptionalDurationtimeoutoptionalDurationtimeoutoptionalDurationTimeoutoptionalDurationTimeoutoptionalDuration= Duration.seconds(30)#
The function execution time (in seconds) after which the WebFunction is terminated.

Must be an integer between 3 and 900 seconds.

webFunctionNameoptionalstringweb_function_nameoptionalstrwebFunctionNameoptionalStringWebFunctionNameoptionalstringWebFunctionNameoptional*string#
The name of the WebFunction.

Default: A unique name is generated by CDK.

Must be 2 to 64 characters of letters, numbers, hyphens or underscores, starting and ending with a letter or number.

Properties ​

The endpoint the WebFunction creates for itself, configured by the endpoint properties in `WebFunctionProps`.

Use its domainName to send requests, and its grants to allow invoking it. Add more endpoints with addEndpoint().

The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

grantPrincipalIPrincipalgrant_principalIPrincipalgrantPrincipalIPrincipalGrantPrincipalIPrincipalGrantPrincipalIPrincipal#
The principal to grant permissions to: the execution role.
logGroupILogGroupReflog_groupILogGroupReflogGroupILogGroupRefLogGroupILogGroupRefLogGroupILogGroupRef#
The log group the WebFunction sends its logs to: the one passed in `logGroup`, or the one created for it.
nodeNodenodeNodenodeNodeNodeNodeNodeNode#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringstatic#
Uniquely identifies this class.
The underlying L1 CfnWebFunction resource.

Use for escape hatches.

resourceRevisionCfnWebFunctionRevisionresource_revisionCfnWebFunctionRevisionresourceRevisionCfnWebFunctionRevisionResourceRevisionCfnWebFunctionRevisionResourceRevisionCfnWebFunctionRevision#
The underlying L1 CfnWebFunctionRevision resource.

Use for escape hatches.

revisionArnstringrevision_arnstrrevisionArnStringRevisionArnstringRevisionArn*string#
The ARN of the WebFunction revision created by this construct.
revisionIdstringrevision_idstrrevisionIdStringRevisionIdstringRevisionId*string#
The ID of the WebFunction revision created by this construct.
rolemay be undefinedIRoleRefrolemay be undefinedIRoleRefrolemay be undefinedIRoleRefRolemay be undefinedIRoleRefRolemay be undefinedIRoleRef#
The execution role of the WebFunction: the one passed in `role`, or the one created for it.
stackStackstackStackstackStackStackStackStackStack#
The stack in which this resource is defined.
webFunctionArnstringweb_function_arnstrwebFunctionArnStringWebFunctionArnstringWebFunctionArn*string#
The ARN of the WebFunction.
webFunctionNamestringweb_function_namestrwebFunctionNameStringWebFunctionNamestringWebFunctionName*string#
The name of the WebFunction.
webFunctionRefWebFunctionReferenceweb_function_refWebFunctionReferencewebFunctionRefWebFunctionReferenceWebFunctionRefWebFunctionReferenceWebFunctionRefWebFunctionReference#
The function's reference.

Ref on AWS::Lambda::WebFunction returns the ARN, so the name is webFunctionName rather than the L1's ref. Resources that should depend on the function take functionArn, a GetAtt on it.

Methods ​

addEndpoint(id: string, options: WebFunctionEndpointOptions): WebFunctionEndpointdef add_endpoint(self, id: str, options: WebFunctionEndpointOptions) -> WebFunctionEndpointpublic WebFunctionEndpoint addEndpoint(String id, WebFunctionEndpointOptions options)public WebFunctionEndpoint AddEndpoint(string id, WebFunctionEndpointOptions options)func AddEndpoint(Id *string, Options WebFunctionEndpointOptions) WebFunctionEndpoint#
Adds an endpoint that serves this function's revision.

Use it to serve the function under a different auth type or endpoint type than endpoint, for example a second, IAM_AUTH endpoint for a CloudFront origin.

addToResourcePolicy(statement: PolicyStatement): AddToResourcePolicyResultdef add_to_resource_policy(self, statement: PolicyStatement) -> AddToResourcePolicyResultpublic AddToResourcePolicyResult addToResourcePolicy(PolicyStatement statement)public AddToResourcePolicyResult AddToResourcePolicy(PolicyStatement statement)func AddToResourcePolicy(Statement PolicyStatement) AddToResourcePolicyResult#
Adds a statement to the WebFunction's resource-based policy.
notes

A web function has a single resource-based policy, so all statements are rendered into one AWS::Lambda::ResourcePolicy. Use it to allow another account, or a service such as CloudFront, to invoke the function's endpoints.

For an imported WebFunction the policy cannot be changed without replacing it, so this adds a warning instead and returns statementAdded: false.

addToRolePolicy(statement: PolicyStatement): voiddef add_to_role_policy(self, statement: PolicyStatement) -> Nonepublic void addToRolePolicy(PolicyStatement statement)public void AddToRolePolicy(PolicyStatement statement)func AddToRolePolicy(Statement PolicyStatement)#
Adds a statement to the WebFunction's execution role.

For an imported WebFunction the role is unknown, so this adds a warning asking for the permission to be granted manually instead.

applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

fromWebFunctionArn(scope: Construct, id: string, webFunctionArn: string): IWebFunction@staticmethod def from_web_function_arn(scope: Construct, id: str, web_function_arn: str) -> IWebFunctionpublic static IWebFunction fromWebFunctionArn(Construct scope, String id, String webFunctionArn)public static IWebFunction FromWebFunctionArn(Construct scope, string id, string webFunctionArn)func FromWebFunctionArn(Scope Construct, Id *string, WebFunctionArn *string) IWebFunctionstatic#
Import an existing WebFunction by its ARN.
fromWebFunctionAttributes(scope: Construct, id: string, attrs: WebFunctionAttributes): IWebFunction@staticmethod def from_web_function_attributes(scope: Construct, id: str, attrs: WebFunctionAttributes) -> IWebFunctionpublic static IWebFunction fromWebFunctionAttributes(Construct scope, String id, WebFunctionAttributes attrs)public static IWebFunction FromWebFunctionAttributes(Construct scope, string id, WebFunctionAttributes attrs)func FromWebFunctionAttributes(Scope Construct, Id *string, Attrs WebFunctionAttributes) IWebFunctionstatic#
Import an existing WebFunction by its attributes.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
isWebFunction(x: any): boolean@staticmethod def is_web_function(x: Any) -> boolpublic static Boolean isWebFunction(Object x)public static bool IsWebFunction(object x)func IsWebFunction(X interface{}) *boolstatic#
Return whether the given object is a WebFunction.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.