Local JavaScript Development CORS Error

I’ve recently been on something of a journey to more formalize my knowledge of frontend development. Most of my work has been in backend development, with just a bit of frontend when I needed to build a full stack application; even in those instances, I tried to mess with the interface as little as possible because it’s not something I’m particularly interested in. However, I decided that I should at least get myself to the point where I can understand most modern frontend code leveraging various frameworks even if I couldn’t create it myself.

I first started with just a refresher in JavaScript in general, and was immediately hit with some information I didn’t realize, such as the fact that putting your <script> tags to load JavaScript files at the very bottom of your HTML was no longer the way to go. Instead, various methods exist to ensure that your JavaScript loads after the everything on the DOM has been rendered but before it becomes problematic. The simplest method is to use the defer keyword:

<script type="text/javascript" src="app.js" defer></script>

However, if you want to be able to use multiple JavaScript files that share information with one another, you should instead add them to the HTML as a module:

That’s:

<script type="module" src="app.js"></script>

However, when just trying to open my index.html file directly in Firefox (the same thing happens in every other browser; I just happened to be using Firefox) to go through some simple exercises and shake off the rust, this gave me a CORS error when attempting to load my JavaScript:

This was… annoying. Even more annoying was that there’s a shocking amount of information on the Internet about how to simply disable CORS protection in your browser… which is an absolutely awful idea if you intend to use that browser for anything other than local web development. CORS exists for a reason, and disabling those protections in the browser is misguided at best. Luckily, there’s an easy solution, which is to simply host the code from a web server. In that instance, the browser will properly detect that everything is coming from the same origin and be happy. While that might sound annoying, it’s trivial to do from any operating system with Python (so everything other than Windows… man Windows sucks.) Python will create a basic web server hosting a directory with the following; note that this assumes my shell is in the directory where my index.html file exists, otherwise that path should be specified after the -d parameter:

python3 -m http.server 8000 -d .

With this up and running, I can direct my browser to http://localhost:8000, and everything works as expected with the CORS protections fully intact.