JavaScript Modules and Cors

javascript modules and CORS

Many browsers do not allow you to access files on the local filesystem with JavaScript (even if the HTML document is also on the local filesystem).

This extends to loading JavaScript modules.

Install a webserver and use that (with a URL like http://localhost/) for testing.

Importing script with type=module from local folder causes a CORS issue

I've googled that for hours and found out that I can host my app by a server (like node.js)

Yes

and then to allow CORS.

Since it will be Same Origin, you won't need CORS.

However I don't want any server. I want just a simple html and a js file.

Then you can't use browser-side ES6 modules.

You'll need to either write the code to not use modules in the first place, or use something like Webpack or Rollup to convert the code to not use modules afterwards.


There is a discussion in the HTML issue tracker about the motivation for the CORS requirement.

Importing js file as module in html gives CORS errors in firefox

According to this article, running modules require a HTTP(s) connection and will not work locally:

If you try to open a web-page locally, via file:// protocol, you’ll
find that import/export directives don’t work. Use a local web-server,
such as static-server or use the “live server” capability of your
editor, such as VS Code Live Server Extension to test modules.

So I'd suggest exactly that and instead of running it locally, use a live server extension from your preferred text editor.

Loading JavaScript in HTML files throws a cross origin request error in local environment only for ES6 modules and not for old JS, why?

Support for cross-origin script loading for non-modules without CORS is a legacy feature for backwards compatibility.

From a discussion during the development of the spec:

The web's fundamental security model is the same origin policy. We
have several legacy exceptions to that rule from before that security
model was in place, with script tags being one of the most egregious
and most dangerous. (See the various "JSONP" attacks.)

Many years ago, perhaps with the introduction of XHR or web fonts (I
can't recall precisely), we drew a line in the sand, and said no new
web platform features would break the same origin policy. The existing
features need to be grandfathered in and subject to carefully-honed
and oft-exploited exceptions, for the sake of not breaking the web,
but we certainly can't add any more holes to our security policy.

That's why, from our perspective, making module scripts bypass the
CORS protocol (and thus the same-origin policy) is a non-starter. It's
not about a specific attack scenario, apart from the ones already
enabled by classic scripts; it's about making sure that new features
added to the platform don't also suffer from the past's bad security
hygiene.



Related Topics



Leave a reply



Submit