CloudFront functions not working at all

0

I have a CloudFront distribution that serves static website from an S3.

I have the following function. I have attached this to Viewer Response in my CloudFront default behaviour. My expectation is if I call my CDN domain with some non-existent path, the response should come with status 200 (since I am rewriting the status in this function). But this is not happening and it keeps returning 404.

async function handler(event) {
      var response = event.response;
      var request = event.request;
     
      var uri = request.uri;

      // If API path, do nothing
      if (uri.startsWith('/api/')) {
        return response;
      }
      
      console.log(response.statusCode)

      // Only rewrite on 403 or 404
      if (response.statusCode === 404 || response.statusCode === 403) {
        response.statusCode = 200;
        response.statusDescription = 'OK';
      }

      return response;
    }
1 Answer
0

Hello,

CloudFront doesn't invoke edge functions for viewer response events when the origin returns HTTP status code 400 or higher [1].

Lambda@Edge functions for origin response events are invoked for all origin responses, including when the origin returns HTTP status code 400 or higher. Hence, you can use Lambda@Edge function at the origin response for your requirement [2].

References :

[1] https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html#function-restrictions-status-codes

[2] https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-generating-http-responses.html#lambda-updating-http-responses

profile picture
answered 7 days ago
AWS
SUPPORT ENGINEER
revised 6 days ago
AWS
SUPPORT ENGINEER
revised 6 days ago
AWS
SUPPORT ENGINEER
revised 6 days ago
  • With test event, the code is behaving as expected.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions