DEV Community

John  Ajera
John Ajera

Posted on

Lambda@Edge: Run Code at the Edge with CloudFront

🚁 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;
};
Enter fullscreen mode Exit fullscreen mode

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
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ 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! πŸ§ πŸš€

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly β€” using the tools and languages you already love!

Learn More

Top comments (0)

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment JosΓ© and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video πŸŽ₯

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere β€œthank you” often brightens someone’s dayβ€”share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay