Failed to load module script: The server responded with a non-JavaScript MIME type of “text/html” in Nginx when deploying an Angular application

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

This happens in Google Chrome and any modern browser that supports JavaScript modules. For example when “building” the Angular 8+ app, this file is usually generated, that is NOT a regular JavaScript file but a JavaScript module.

polyfills-es2015.js:1 

There are two important parts to solve this problem:

Solution Part 1. Set the “base-href” to the same sub directory that is inside of your “dist” directory.

Angular 8+ exports your application into a “dist/my-app-sub-directory”, notice there is now a sub directory inside “dist” (in previous versions of Angular your app was exported in “dist” directly, that’s not the case anymore). In order to fix this problem be sure  you use the flag to configure the base-href as follows:

ng build --prod --baseHref=/my-app-sub-directory/

For a complete working example using multi-lingual configurations check this repository out.

Solution Part 2. If after setting the base-href you are still getting a similar error, try to indicate to your server how to “manage” JavaScript modules.

In Nginx that can be done using a configuration such as this one in your server block:

location ~ \.js {
   add_header Content-Type text/javascript;
}

See the full server block configuration file for Nginx here.

If you are looking for something just for development purposes Live Server + a custom middleware can do the job.

Check this example of a custom middleware. Run it with:

node node-scripts/live-server.js

That’s it. See you next time!

3 comments on “Failed to load module script: The server responded with a non-JavaScript MIME type of “text/html” in Nginx when deploying an Angular application”

Leave a Reply

Your email address will not be published. Required fields are marked *