Reputation: 2190
I currently have two Lambda@Edge functions:
The current flow is:
viewer request -> language-redirect
if 302 -> viewer response
if not 302 -> pass on to CloudFront -> HSTS -> viewer response
Would it be possible to combine both in one function (combined) that is invoked only a single time per viewer request?
viewer request -> combined
if 302 -> viewer response
if not 302 -> pass on to CloudFront -> combined -> viewer response
The goal is to have the same function invoked once, not having the same function invoked twice.
Upvotes: 1
Views: 1947
Reputation: 179294
There are 4 distinct trigger events in CloudFront's Lambda@Edge enhancement. Their interaction with the cache is in bold, and becomes important, later:
One Lambda function, correctly written to understand where it has been fired within the transaction cycle, can be triggered at any combination of these points -- but since these events all occur at different times, it isn't possible to handle more than a single event with one invocation of the trigger function.
However, note the points in bold, above. You can substantially reduce the number of trigger invocations in many cases by using the origin-side triggers. As noted above, using these triggers results in the response of the triggers being cacheable -- so when your redirect trigger fires, if it generates a redirect, the redirect can be cached, and the next request doesn't need to invoke the trigger at all. Similarly, adding your HSTS header to a cacheable response in an origin response trigger means that future cache hits will return the modified response with HSTS headers, without the trigger firing.
Update: in 2021, CloudFront (finally!) launched a new feature called response header policies, which allows you to configure static HTTP response headers as part of the CloudFront distribution. This allows adding of static response headers, such as for HSTS (as mentioned in the original question), without using Lambda@Edge or CloudFront Functions.
Upvotes: 7