Safari does not include cookies when requesting es2015 module files

Viewed 1462

My webserver requires that an authentication cookie be present before serving any file, including .js files.

Since updating one of my sites to offer es2015 modules in a <script type="module"> tag, the authentication cookie is not sent with the request for that file by Safari. It works as expected in Chrome.

Is there a behavior in Safari that is blocking cookies on js module requests? I can rollback to not supporting modules to restore service but then loose the module benefits for browsers which support them.

<script src="module.js" type="module"></script>
<script src="legacy.js" nomodule></script>
---
<script src="legacy.js"></script>

First party cookies are set in the headers of the server's response for the page requesting the js files. When the first two script tags are present, Safari requests module.js not legacy.js, as expected, but does not include any cookies with that request. If the third script tag is used instead, Safari requests legacy.js, including the cookies with that request.

Is there a way to get Safari to send cookies with the module request? Is there risk that other browsers will adopt Safari's behavior? Does the ECMAScript 6 specification prescribe the behavior here one way or another?

1 Answers

Module scripts and their dependencies are fetched with CORS. This means that any cross-origin module scripts must be served with the proper headers, such as Access-Control-Allow-Origin: *. Of course, this is not true for classic scripts.

An option that seems to work for the time being is to add the type module attribute on your script

<script src="[...].js" type="module" crossorigin="use-credentials"></script>

By default (that is, when the attribute is not specified), CORS is not used at all. The "anonymous" keyword means that there will be no exchange of user credentials via cookies, client-side SSL certificates or HTTP authentication, unless it is in the same origin.

The use-credentials value must be used when fetching a manifest that requires credentials, even if the file is from the same origin. https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes

Related