As I recently migrated my homepage to the AWS cloud using Cloudfront and S3, I ran into a pickle. The website backend is the static website hosting feature from S3, which has the interesting characteristic that (in most cases) unless the Content-Type is explicitly declared on the bucket object, you’ll get `application/octet-stream’ instead.

This was an issue, because it caused my WASM programs (e.g. Juoni) to cease working properly due to strict MIME-type checking. After looking up solutions of all kinds, I figured out that the best solution in my case would be a Lambda. With Lambda@Edge, it was possible to hook a helper script up to CloudFront.

Using Python 3.6 runtime, copy-paste following to an Origin Response script. You can use the CloudFront template, with no further permissions or other work needed other than deploying it to relevant distributions.

import json
import mimetypes

def lambda_handler(event, context):
    request = event['Records'][0]['cf']['request']
    request_uri = request['uri']
    response = event["Records"][0]["cf"]["response"]
    headers = response["headers"]
    if "content-type" in headers:
        # If this is an octet-stream, void it
        if headers["content-type"][0]["value"] == "application/octet-stream":
            del headers["content-type"]
    # Check that a Content-Type doesn't exist. If it does, do nothing
    if not "content-type" in headers:
        mime, encoding = mimetypes.guess_type(request_uri)
        if mime is not None:
            headers["content-type"] = [{"key": "Content-Type", "value": mime}]
            if encoding is not None:
                headers["content-encoding"] = [{"key": "Content-Encoding", "value": encoding}]
    return response

Hopefully this helps others experiencing the same issue!

- Arttu

© Arttu Ylä-Sahra 2016-2021
Page rendered on 2021-02-16T14:21:40.875+00:00