Search code examples
amazon-cloudfront

How to generate a 404 page from a CloudFront Function?


I would like to generate a 404 page from a Cloudfront Function for some well-known paths. So far I am able to generate the 404 response with the enclosed pseudo code, but without any body. The documentation suggests it is possible, but there are no examples around.

function handler(event) {
    
    // NOTE: This example function is for a viewer request event trigger. 
    // Choose viewer request for event trigger when you associate this function with a distribution. 
    var request = event.request, response = event.response;
    
   
    if (URL_IS_FORBIDDEN) {
        return {
            statusCode: 404,
            statusDescription: "Not Found",
        };
    } else  {
        return request;
    }     
}

If I try to assign body or text, cloudfront says the property does not exist, and indeed it is not mentioned in the docs.

So can I output a body from the cloudfront function?


Solution

  • You can't currently return a response body from a CloudFront Function (see below). But you can either 1/ Use a Lambda@Edge function, or 2/ Override the request URI to point to the 404 URL at your origin.

    For number 2, if your 404 file is located at /pages/404.html at your origin (e.g., on S3), you could use a CloudFront Function like this:

    function handler(event) {
        var request = event.request;
        
        // Route the request to a 404 page if the URL is not found.
        if (URL_IS_FORBIDDEN) {
            request.uri = '/pages/404.html';
        } 
        return request;
    }
    

    When you modify an HTTP response with CloudFront Functions, you cannot alter or modify the response body. If you need to alter the response body, use Lambda@Edge. With Lambda@Edge, you can replace the entire response body with a new one, or remove the response body.

    https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/writing-function-code.html