Search code examples
amazon-web-servicesaws-lambdaamazon-cloudfrontaws-serverlessaws-lambda-edge

AWS serverless - Modify cloudfront POST request to a GET Request for s3 website origin


I have a CloudFront distribution where the origin is set to an s3 website endpoint (serving static web app on s3)

Now my webapp on s3 needs some user information that is only provided via a POST request from an iframe.

I thought it would be possible to use Lambda@edge function on ViewerRequest stage, to capture the user info, and then modify the request to GET and append a token to the origin, before it requests the origin, thus allowing s3 to serve.

However i can't seem to get it to work. is this even possible?


Solution

  • You can't change the HTTP method in a Lambda@Edge trigger function, because it is read-only.

    method (read-only)

    The HTTP method of the viewer request.

    https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html#lambda-event-structure-request

    What you can do is use the AWS SDK to send a request to S3 from within the trigger function, and use the object content retrieved, to generate a response directly from the trigger function.

    Note that there are limits to the response size you can generate -- for Viewer Request, it's 40KB. For Origin Request, it's 1MB.

    Of course, you don't need to fetch the content from S3, necessarily. You can fetch it from anywhere, or you can embed it in the function itself.

    With this setup, since the function is generating a response, CloudFront never forwards the actual POST request to S3.