🚁 Lambda@Edge: Run Code at the Edge with CloudFront

Lambda@Edge brings the power of serverless computing closer to your users by running AWS Lambda functions at CloudFront edge locations around the world. That means lower latency, personalized responses, and enhanced security — all without managing infrastructure.


🚀 What is Lambda@Edge?

Lambda@Edge extends AWS Lambda to CloudFront, allowing you to execute code at the edge, near the user. Instead of sending every request to a central region or origin server, you can run logic immediately at the request/response boundary.

🔧 Common Use Cases

  • ✅ Redirects and URL rewrites
  • ✅ Authentication and authorization at the edge
  • ✅ Injecting security headers
  • ✅ Geo-targeted content
  • ✅ A/B testing

🛁 How It Works

Lambda@Edge functions are associated with specific CloudFront events:

Event Type When It Happens
viewer-request Before CloudFront checks its cache
origin-request Before forwarding the request to origin
origin-response After the origin returns the response
viewer-response Before returning response to the viewer

🔒 Example: Add Security Headers

exports.handler = async (event) => {
  const response = event.Records[0].cf.response;
  response.headers['strict-transport-security'] = [{
    key: 'Strict-Transport-Security',
    value: 'max-age=63072000; includeSubdomains; preload'
  }];
  response.headers['x-content-type-options'] = [{
    key: 'X-Content-Type-Options',
    value: 'nosniff'
  }];
  return response;
};

Attach this function to the viewer-response event.


🌍 Deploying with Terraform

provider "aws" {
  region = "us-east-1" # Required for Lambda@Edge
}

resource "aws_iam_role" "lambda_edge" {
  name = "lambda-edge-role"
  assume_role_policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Action = "sts:AssumeRole",
        Effect = "Allow",
        Principal = {
          Service = [
            "lambda.amazonaws.com",
            "edgelambda.amazonaws.com"
          ]
        }
      }
    ]
  })
}

resource "aws_lambda_function" "edge_function" {
  filename         = "lambda.zip"
  function_name    = "edge-header-fn"
  handler          = "index.handler"
  runtime          = "nodejs18.x"
  role             = aws_iam_role.lambda_edge.arn
  publish          = true # Required
}

resource "aws_cloudfront_distribution" "cdn" {
  # Your origin and behavior config...

  default_cache_behavior {
    target_origin_id = "origin1"

    lambda_function_association {
      event_type   = "viewer-response"
      lambda_arn   = aws_lambda_function.edge_function.qualified_arn
      include_body = false
    }
  }
}

💡 You must deploy Lambda@Edge functions in us-east-1 and use a published version, not $LATEST.


⚠️ High-Level Limitations

  • 🔹 Must be deployed in us-east-1
  • 🔹 Requires published version (not $LATEST)
  • 🔹 Limited runtime support (Node.js and Python only)
  • 🔹 No support for VPC, env vars, layers, container images, or custom runtimes
  • 🔹 Propagation delays after update due to edge replication

More here: Lambda@Edge Restrictions →


🧠 Runtime Support

Lambda@Edge currently supports only the following runtimes:

Runtime Supported?
nodejs18.x
nodejs16.x
python3.9
python3.8
Go, Java, .NET, Ruby, etc. ❌ Not supported
Custom runtimes, container images ❌ Not supported

📌 No Go, Java, or custom runtimes. AWS has not announced plans for additional runtime support.

Alternatives:

  • 🧠 CloudFront Functions (JavaScript-only)
  • 🧠 Fastly Compute@Edge or Cloudflare Workers
  • 🧠 Regular Lambda + API Gateway (if latency is acceptable)

✅ When Should You Use Lambda@Edge?

Use it when you need:

  • Low-latency, globally distributed logic
  • Lightweight request/response transformations
  • Offloading processing from origin servers
  • Better control over caching behavior

📚 Learn More


Drop a comment or follow for more AWS serverless deep dives! 🧠🚀