Cloudfront Function always returns 503

Viewed 639

How do you set a default root object for subdirectories for a statically hosted website on Cloudfront?

This is a known issue but what I want to know is, how to set up the lambda in CDK. I have used the solution below but when I access the site I get a 503 response

The CloudFront function returned an invalid value: response.statusCode is missing

Testing this in the AWS console is successful so why wouldn't it work on the hosted site?

redirect handler

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

  // Check whether the URI is missing a file name.
  if (uri.endsWith('/')) {
    request.uri += 'index.html';
  }
  // Check whether the URI is missing a file extension.
  else if (!uri.includes('.')) {
    request.uri += '/index.html';
  }
  return request;
}

cloudfront setup

myFunction = new Function(this, 'ViewerResponseFunction', {
          functionName: 'RedirectURIFunction',
          code: FunctionCode.fromFile({filePath: myFilePath}).render(),
          comment: "Comment about the function"
    });

originConfigs: [
  {
    s3OriginSource: {
      s3BucketSource: myBucket,
      originAccessIdentity: myOAI,
    },
    behaviors: [{
      functionAssociations: [{
         function: myCfnFunction,
         eventType: FunctionEventType.VIEWER_RESPONSE
      }],
      isDefaultBehavior: true
    }]
]}
1 Answers

From the restrictions page of Lambda@Edge

The Lambda function must be in the US East (N. Virginia) Region.

Your code will be still executed in the closest in the closest Edge location to the user, but the function itself must be located in us-east-1.

Based on your usecase (which seems to be a simple url redirect) you might want to consider using the newer CloudFront Functions feature, which is faster and more lightweight. This documentation page has a good comparison table.

Edit:

I haven't used CloudFront functions before, but looking at the CDK documentation and your link, I can suggest a few changes.

    myFunction = new Function(this, 'ViewerResponseFunction', {
          functionName: 'RedirectURIFunction',
          code: FunctionCode.fromFile({filePath: myFilePath}).render(),
          comment: "Comment about the function"
    });
originConfigs: [
  {
    s3OriginSource: {
      s3BucketSource: myBucket,
      originAccessIdentity: myOAI,
    },
    behaviors: [{
      functionAssociations: [{
         function: myFunction,
         eventType: FunctionEventType.VIEWER_REQUEST
      }],
      isDefaultBehavior: true
    }]
]}
Related