AWS Cloudfront serving javascript modules as wrong MIME type( "Text/Plain")

Viewed 1687

I have a Vue app hosted on an Amazon S3 bucket. It is loading great when accessed via the S3 link w/http. When I visit the site via a custom SSL domain link to cloudfront the javascript isn't served correctly. the JS files are fully accessible via https in the browser, but don't execute in the browser, leaving me with a blank page. I'm getting the following error for both javascript links in the index.html:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec.

also: I was following the instructions here: https://levelup.gitconnected.com/deploying-vue-js-to-aws-with-https-and-a-custom-domain-name-3ae1f79fe188

3 Answers

Figured it out, I just had to manually change the system-defined content type in the S3 console for the individual js objects from text/plain to application/javascript, then make sure the cache was invalidated and refreshed on my browser.

If uploading via the aws command line tool you can make it upload javascript files with the correct mime/content type with a registry edit.

Modify the registry key

HKEY_CURRENT_USER\SOFTWARE\Classes.js

Set "Content Type" to "application/javascript"

Note: The last Windows update (as of 2022-01-14) quietly reverted this registry entry to "text/plain".

AWS S3 determines the default "content-type" metadata for the js files to be "text/plain" during upload. A workaround to fix such types of issues is to upload files to s3 and specify the content-type in metadata for js files explicitly. Eg.

aws s3 sync $DIST_PATH/ s3://$BUCKET_NAME/ --exclude "*.js"
aws s3 sync $DIST_PATH/ s3://$BUCKET_NAME/ --include "*.js" --content-type "application/javascript"
aws cloudfront create-invalidation --distribution-id $DISTRIBUTION_ID --paths
Related