2022-09-30

Why do I get MIME type error on Django/React app when loading css/js from Aws?

So I deployed a Django-Rest/React app on Heroku where I serve my static and media files on AWS S3 buckets. After pushing to Heroku and accessing the API URL or admin URL everything works fine but when I try to access my React URLs I get a MIME type error.

On the network tab of developer tools, I get status 301 on my JS and CSS file.

And in the console I get:

Refused to apply style from 'https://app.herokuapp.com/static/css/main.9d3ee958.css/' because its MIME type 
('text/html') is not a supported stylesheet MIME type, and strict MIME checking is 
enabled.
app.herokuapp.com/:1 Refused to apply style from 'https://app.herokuapp.com/static/css/main.9d3ee958.css/' because its MIME type 
('text/html') is not a supported stylesheet MIME type, and strict MIME checking is 
enabled.
app.herokuapp.com/:1 Refused to execute script from 'https://app.herokuapp.com/static/js/main.3b833115.js/' because its MIME type 
('text/html') is not executable, and strict MIME type checking is enabled.

Even though the URL above is correct and I do have those files in my bucket.

Here are my production settings:

from decouple import config
import django_heroku
import dj_database_url
from .base import *


 SECRET_KEY = config('SECRET_KEY')
 DEBUG = False

 ALLOWED_HOSTS = ['*']

 ROOT_URLCONF = 'portfolio.urls_prod'

 TEMPLATES = [
     {
         'BACKEND': 'django.template.backends.django.DjangoTemplates',
         'DIRS': [
             os.path.join(BASE_DIR, 'frontend/build')
         ],
         'APP_DIRS': True,
         'OPTIONS': {
             'context_processors': [
                 'django.template.context_processors.debug',
                 'django.template.context_processors.request',
                 'django.contrib.auth.context_processors.auth',
                 'django.contrib.messages.context_processors.messages',
             ],
         },
     },
 ]

 # DATABASE
 DATABASES = {}
 DATABASES['default'] = dj_database_url.config(conn_max_age=600)

 # HEROKU
 django_heroku.settings(locals())

 # AWS S3 SETTINGS
 AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
 AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
 AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
 AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
 AWS_DEFAULT_ACL = 'public-read'

 AWS_S3_OBJECT_PARAMETERS = {
     'CacheControl': 'max-age=86400',
 }
 AWS_HEADERS = {
     'Access-Control-Allow-Origin': '*',
 }
 AWS_QUERYSTRING_AUTH = False

 # AWS STATIC SETTINGS
 AWS_LOCATION = 'static'
 STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
 STATICFILES_STORAGE = 'portfolio.storage_backend.StaticStorage'

 # AWS MEDIA SETTINGS
 DEFAULT_FILE_STORAGE = 'portfolio.storage_backend.MediaStorage'
 MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, 'media')


 STATICFILES_DIRS = [
     os.path.join(BASE_DIR, 'frontend/build/static'),
 ]

 # HEROKU LOGGING
 DEBUG_PROPAGATE_EXCEPTIONS = True

 LOGGING = {
     'version': 1,
     'disable_existing_loggers': False,
     'formatters': {
         'verbose': {
             'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
             'datefmt' : "%d/%b/%Y %H:%M:%S"
         },
         'simple': {
             'format': '%(levelname)s %(message)s'
         },
     },
     'handlers': {
         'console': {
             'level': 'DEBUG',
             'class': 'logging.StreamHandler',
         },
     },
     'loggers': {
         'MYAPP': {
             'handlers': ['console'],
             'level': 'DEBUG',
         },
     }
 }


 # HTTPS SETTING
 SESSION_COOKIE_SECURE = True
 CSRF_COOKIE_SECURE = True
 SECURE_SSL_REDIRECT = True


 # HSTS SETTINGS
 SECURE_HSTS_SECONDS = 31536000 # 1 year
 SECURE_HSTS_PRELOAD = True
 SECURE_HSTS_INCLUDE_SUBDOMAINS = True


 options = DATABASES['default'].get('OPTIONS', {})
 options.pop('sslmode', None)

This is my storage_backend.py code:

from storages.backends.s3boto3 import S3Boto3Storage

class MediaStorage(S3Boto3Storage):
    location = 'media'
    file_overwrite = False

class StaticStorage(S3Boto3Storage):
    location = 'static'
    default_acl = 'public-read'

This is my url_prod.py code:

from django.contrib import admin
from django.urls import path, re_path, include
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
  path("admin/", admin.site.urls),
  path('api/', include('api.urls')),

  re_path(r'^(?P<path>.*)/$', TemplateView.as_view(template_name='index.html')),
  path('', TemplateView.as_view(template_name='index.html')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This is my bucket policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket-name/*"
        }
    ]
}

EDIT:

I checked the network tab in developer tools and realized that my staticfiles from admin are being served from my was bucket:

Request URL: 
https://bucket-name.s3.amazonaws.com/static/admin/css/base.css
Request Method: GET
Status Code: 200 OK (from disk cache)
Remote Address: 52.95.143.47:441
Referrer Policy: same-origin

But the static files for my React views are not:

Request URL: 
https://app.herokuapp.com/static/css/main.9d3ee958.css
Request Method: GET
Status Code: 301 Moved Permanently
Remote Address: 54.224.34.30:441
Referrer Policy: same-origin


No comments:

Post a Comment