Edge lambda functions



An Edge Lambda Function is a compute resource that runs your code at CDN edge locations, bringing it closer to your users to reduce latency and improve performance. These functions are globally distributed, ensuring that requests are handled by the nearest location.

Edge Lambdas are serverless, which means Stacktape manages the infrastructure, security, and scaling for you. They support Node.js and Python runtimes and follow a pay-per-use model, so you only pay for the execution time you consume.

Common use cases include user authentication, request validation, and cookie manipulation.

Under the hood

Stacktape uses Lambda@Edge to power Edge Lambda Functions. These functions are associated with a CDN and are triggered by CDN events—either when a request is made to the CDN (onRequest) or when the CDN is about to send a response back to the user (onResponse).

When to use

Advantages

  • Low latency: By executing code closer to the end-user, you can significantly improve your application's performance.
  • Scalability: Edge Lambdas automatically scale with the number of incoming requests.
  • Pay-per-use: You are billed only for the compute time you use, measured in milliseconds.

Disadvantages

  • Limited execution environment: Edge lambdas triggered by onRequest or onResponse events are limited to 128MB of memory and a 5-second maximum execution time.

Basic usage

  • onRequest: Before cache lookup — modify the request, add auth, or return early.
  • onResponse: Before returning to the client — modify headers, add cookies.

In the following example, an Edge Lambda Function validates the Authorization header of each incoming request. If the header is missing or invalid, the user is redirected to a login page.

resources:
  authFunction:
    type: edge-lambda-function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: auth-function.ts

  myBucket:
    type: bucket
    properties:
      cdn:
        enabled: true
        edgeFunctions:
          onRequest: authFunction
const validateAuthorizationToken = (token) => {
  // perform some validation
  return true;
};

export default async (event) => {
  const { request } = event.Records[0].cf;
  const { headers } = request;

  const authorizationToken = headers.authorization?.[0]?.value;

  const userAuthorized = validateAuthorizationToken(authorizationToken);

  // if user is not authorized, redirect him to login page
  if (!userAuthorized) {
    return {
      status: '302',
      headers: {
        location: [
          {
            key: 'Location',
            value: '/login'
          }
        ],
        'cache-control': [
          {
            key: 'Cache-Control',
            value: 'no-cache, no-store, max-age=0, must-revalidate'
          }
        ]
      }
    };
  }

  // after we validated that user is authorized, we can return the request
  // request will be forwarded to origin
  return request;
};

Code of the authFunction authorizer.

EdgeLambdaFunctionAPI reference
typeRequired
No description

Type: string "edge-lambda-function"

properties.packagingRequired

How the function code is packaged and deployed.

Type: LambdaPackaging

properties.runtime

Lambda runtime. Auto-detected from file extension. Edge functions support Node.js and Python only.

Type: string ENUM

Possible values: nodejs18.xnodejs20.xnodejs22.xnodejs24.xpython3.10python3.11python3.12python3.13python3.8python3.9

properties.memoryDefault: 128

Memory in MB. Max depends on event type: viewer events = 128 MB, origin events = 10,240 MB.

Type: number

properties.timeoutDefault: 3

Max execution time in seconds. Viewer events: max 5s. Origin events: max 30s.

Type: number

properties.connectTo

Grant access to other resources in your stack (IAM permissions only — no env vars or VPC access).

Type: Array of string

Edge Lambda functions cannot use environment variables or connect to VPC resources. connectTo only sets up IAM permissions (e.g., S3 bucket access, DynamoDB, SES).

properties.iamRoleStatements

Custom IAM policy statements for fine-grained AWS permissions beyond what connectTo provides.

Type: Array of StpIamRoleStatement

properties.logging

Logging config. Logs are sent to CloudWatch in the region where the function executed (not your stack region).

Type: LambdaFunctionLogging

overrides

Escape hatch to modify the underlying CloudFormation resources Stacktape creates.

Type: Object

Use dot-notation paths to override specific properties on any child resource. Find resource logical IDs with stacktape stack-info --detailed.

overrides:
  MyDbInstance:
    Properties.StorageEncrypted: true

Event structure

The event payload delivered to your function depends on the trigger:

On request trigger

When a function is triggered by an onRequest event, you can either:

  1. Return a response directly from the function: This bypasses the origin and serves the response immediately to the client.
  2. Modify the request and forward it to the origin: You can alter the request (e.g., add headers) before it continues to the origin.

The following example demonstrates both:

const validateAuthorizationToken = (token) => {
  // perform some validation
  return true;
};

export default async (event) => {
  const { request } = event.Records[0].cf;
  const { headers } = request;

  const authorizationToken = headers.authorization?.[0]?.value;

  const userAuthorized = validateAuthorizationToken(authorizationToken);

  // if user is not authorized, redirect him to login page
  if (!userAuthorized) {
    return {
      status: '302',
      headers: {
        location: [
          {
            key: 'Location',
            value: '/login'
          }
        ],
        'cache-control': [
          {
            key: 'Cache-Control',
            value: 'no-cache, no-store, max-age=0, must-revalidate'
          }
        ]
      }
    };
  }

  // after we validated that user is authorized, we can return the request
  // request will be forwarded to origin
  return request;
};

If the user is authorized, the request is forwarded to the origin. Otherwise, a redirect response is returned.

resources:
  authFunction:
    type: edge-lambda-function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: auth-function.ts

  myBucket:
    type: bucket
    properties:
      cdn:
        enabled: true
        edgeFunctions:
          onRequest: authFunction

Example configuration for the authorizer function.

On response trigger

A function triggered by an onResponse event can modify the response from the origin before it's sent to the client. In this example, the function adds a Set-Cookie header to the response:

export default async (event) => {
  const { response } = event.Records[0].cf;

  response.headers['set-cookie'] = [
    {
      key: 'Set-Cookie',
      value: 'my-experimental-cookie=cookie-value'
    }
  ];

  return response;
};

Code for the function that sets a cookie.

resources:
  cookieFunction:
    type: edge-lambda-function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: set-cookie.ts

  myBucket:
    type: bucket
    properties:
      cdn:
        enabled: true
        edgeFunctions:
          onResponse: cookieFunction

Example configuration for the onResponse trigger.

Packaging

Packaging for Edge Lambda Functions follows the same process as for regular Lambda functions. For more details, see the packaging documentation.

For functions triggered by onRequest or onResponse, the zipped package size cannot exceed 1MB.

Logging

Logging config. Logs are sent to CloudWatch in the region where the function executed (not your stack region).

LambdaFunctionLoggingAPI referenceParent:EdgeLambdaFunction
disabled

Disable CloudWatch logging entirely.

Type: boolean

retentionDaysDefault: 180

How many days to keep logs. Longer retention = higher storage cost.

Type: number ENUM

Possible values: 13571430609012015018036540054573118273653

logForwarding

Forward logs to an external service (Datadog, Highlight.io, or any HTTP endpoint).

Type: HttpEndpointLogForwarding or HighlightLogForwarding or DatadogLogForwarding

Uses Kinesis Data Firehose (~$0.03/GB). Failed deliveries go to a backup S3 bucket.

Accessing other resources

By default, Edge Lambda Functions cannot access other AWS resources. Permissions must be granted explicitly using IAM. Stacktape automatically handles permissions for essential services like logging.

You can grant additional permissions in two ways:

Using connectTo

The connectTo property simplifies granting access to other Stacktape-managed resources. It automatically configures the necessary IAM permissions and injects environment variables with connection details.

resources:
  authFunction:
    type: edge-lambda-function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: auth-function.ts
      connectTo:
        # access to the dynamo table
        - myDynamoTable
        # access to AWS SES
        - aws:ses

  myDynamoTable:
    type: dynamo-db-table
    properties:
      primaryKey:
        partitionKey:
          name: id
          type: string

Edge Lambda functions cannot use environment variables or connect to VPC resources. connectTo only sets up IAM permissions (e.g., S3 bucket access, DynamoDB, SES).

Using iamRoleStatements

For more granular control, you can provide raw IAM role statements to define custom permissions.

Be mindful of latency when accessing other resources. While your stack is deployed in a specific region, your Edge Lambda may execute in a different edge location across the globe, which can increase the time it takes to communicate with your other resources.

API reference

StpIamRoleStatementAPI referenceParent:EdgeLambdaFunction
ResourceRequired

ARNs of the AWS resources this statement applies to. Use "*" for all resources.

Type: Array of string

Sid

Optional identifier for this statement (for readability).

Type: string

EffectDefault: Allow

Whether to allow or deny the specified actions.

Type: string

Action

AWS actions to allow or deny (e.g., s3:GetObject, sqs:SendMessage).

Type: Array of string

Condition
No description

Type: UNSPECIFIED