FrontendAWS

Next.js SSR Optimization with CloudFront and Lambda@Edge

NT

Naveen Teja

2/27/2026

Next.js SSR Optimization with CloudFront and Lambda@Edge

Hosting a Next.js application on AWS requires strategic architectural decisions to ensure low latency for global users. While static assets can be served directly from S3, Server-Side Rendered (SSR) pages require dynamic compute execution for every request.

To optimize performance, you can deploy a CloudFront distribution as your global Content Delivery Network (CDN) and attach Lambda@Edge functions to specific cache behaviors. Lambda@Edge executes compute logic at the AWS edge locations closest to your users, allowing you to manipulate requests, handle authentication, or perform A/B testing before the request ever reaches your origin server.

When defining this in Terraform, you must deploy the Lambda function to the us-east-1 region (a strict requirement for Lambda@Edge) and publish a specific version of the function. You then reference that version ARN inside the CloudFront default cache behavior using a `lambda_function_association` block.

lambda-edge.tf
resource "aws_cloudfront_distribution" "nextjs" {
  # ... origin configuration ...

  default_cache_behavior {
    target_origin_id       = "NextJsOrigin"
    viewer_protocol_policy = "redirect-to-https"
    
    # Execute Edge logic on every Viewer Request
    lambda_function_association {
      event_type   = "viewer-request"
      lambda_arn   = aws_lambda_function.edge_auth.qualified_arn
      include_body = false
    }
  }
}